CS1061 C Programmuing Lecture 12 Arrays

Download Report

Transcript CS1061 C Programmuing Lecture 12 Arrays

CS1061 C Programmuing
Lecture 12 Arrays
A. O’Riordan, 2004
Arrays
Grouping of consecutive memory locations with same name and type.
To refer to an element, specify the array name and a position number.
Format:
arrayname[position number]
First element always at position 0.
n element array named c: c[0], c[1]...c[n – 1]
c[0]
c[n]
Declaring Arrays
Declaring arrays is similar to declaring simple variables. Specify size in square
brackets, size must be integet constant.
int arr[10];
float samples[3284];
Declaring multiple arrays of same type on a single line:
int x[100], y[27];
A define directive is often used to specifiy the size.
#define MAX_SIZE 100
...
double readings[MAX_SIZE];
Array Example
Suppose you want to write a program that will store values for the salaries of
employees. You could create a variable for each employee but that would be a
lengthy process and there would be no way to access these variables without
explicitly referencing them. In C we use arrays.
double salaries[NUM_EMPLOYEES];
If no size is given the array can hold no values.
To access elements of the vector you use the array-indexing [] operator. The value
given to the [] operator is called the subscript. Here are examples:
salaries[0] = 42000.00;
printf("Jim Smith's salary: %f\n", salaries[0]);
Arrays and for Loops
It is very common to see arrays and for loops used together.
The for loop is ideal for stepping through the elements of an array.
For example, you can use a for loop to initialize each value to zero like this:
int int_array[100], i;
for( i=0; i < 100; i++)
int_array[i] = 0;
Errors involving the access of non-existent slots, especially out-by-one errors are
common. Here is an example of a bounds error:
int_array[100] = 5; /* error only 0 to 99 are valid */
Array Initialisation
The values in an array can be initialised in the declaration. Listing the values in
curly braces does this.
int digits[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
When initialisations are provided it is legal to omit the array size indicator from
the declaration as in
int digits[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
If arrays are declared in this way you can calculate how many elements are in the
array with the sizeof operator
printf(“size is %d",(sizeof digits)/(sizeof digits[0]);
Passing Arrays to Functions
To pass an array argument to a function, specify the name of the array without any
brackets
int myArray[24];
modifyArray(myArray, 24);
Array size usually passed to function as a separate parameter
The size does not need to be given in a function prototype
void modifyArray( int b[], int arraySize);
Parameter names are also optional in prototype, e.g. int b[] could be written int []
void modifyArray( int [], int);
Searching Arrays
Search an array for a certain value
Linear search- Compare each element of array with key value
Useful for small and unsorted arrays
Binary search - for sorted arrays
Algorithm:
Compares middle element with key
If equal, match found
If key < middle, looks in first half of array
If key > middle, looks in last half
Repeat
Very fast; at most n steps, where 2n > number of elements
e.g. 30 element array takes at most 5 steps
Multidimensional Arrays
In short, multidimensional arrays are arrays of arrays. They are very useful in
scientific applications where you have tables of data such as matrices.
int list[10]; /* A 1-dimensional array */
int matrix[10][10];
/* A 2-dimensional array */
matrix can be viewed as a 1-d array of lenght 10 of arrays matrix[10].
You can think of two dimensional arrays as a grid. You have ten rows and ten
columns, for a total of 100 elements. Indexing is again from 0.
Application: Chess
The following declares a 2-dimensional array that represents a chessboard, i.e. 8x8
elements for the 64 squares:
char chessBoard[8][8];
In the game of chess one player plays the white pieces and the other plays the
black pieces. Let white's pieces be represented in capitals, e.g. white's queen is
Q, and let black's pieces be represented in lower-case letters, e.g. black's queen
is q. To set up the board, we want to place one of white's rooks (R) in the
bottom right square, one of the knight (N) in the square immediately to the
right, etc.
chessBoard[7][0] = 'R';
chessBoard[7][1] = ‘N';
/* white rook */
/* white knight */
Application: Chess (2)
We can also encode the start state of chess game into a single initialiser:
char
{
{
{
{
{
{
{
{
};
chessBoard[8][8] = {
'r', 'n', 'b', 'q', 'k',
'p', 'p', 'p', 'p', 'p',
' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ',
'P', 'P', 'P', 'P', 'P',
'R', 'N', 'B', 'Q', 'K',
'b',
'p',
' ',
' ',
' ',
' ',
'P',
'B',
'k',
'p',
' ',
' ',
' ',
' ',
'P',
'N',
'r'
'p'
' '
' '
' '
' '
'P'
'R'
},
},
},
},
},
},
},
}
Eliding Braces
The braces in initialisations can be elided except for the outer-most braces, e.g.
int matrix[2][2] = {1, 2, 3, 4};
/* instead of {{1, 2}, {3, 4}} */
We know that digits[0] returns the first element in the array digits. But what be the
value of the following expression
digits
This in fact returns the memory address of the first element; so it is in fact
equivalent to &digits[0]. The & is the address-of operator (see later).