8. ARRAYSOne-Dimensional ArraysArray SubscriptingSlide 4Slide 5Multidimensional ArraysSlide 7Initializing an ArraySlide 9Variable-Length Arrays (C99 Only)8. ARRAYSOne-Dimensional Arrays•A one-dimensional array is declared in the following way:int a[10];The number 10 declares that a will have ten elements.•Array bounds always start at 0, so a has the following appearance:Notice that 10 is the length of the array, not the array’s upper bound.Array Subscripting•To select an element of an array, use the [] operator:a[0]a[i]a[i*2+1]This operation is called array subscripting.Array Subscripting•Example of array subscripting:#include <stdio.h>#define N 100int main(void){int a[N], i, sum;printf("Enter %d numbers: ", N);for (i = 0; i < N; i++)scanf("%d", &a[i]);sum = 0;for (i = 0; i < N; i++)sum += a[i];printf("Sum is %d\n", sum);printf("Average is %d\n", sum/N);return 0;}Array Subscripting•Warning: Array bounds are not checked; when a subscript goes out of bounds, the result is unpredictable. One common cause of a subscript out of bounds: forgetting that an array with n elements is indexed from 0 to n–1, not 1 to n. On some systems, the following innocent-looking for statement causes an infinite loop:int a[10], i;for (i = 1; i <= 10; i++) a[i] = 0;Multidimensional Arrays•Arrays may have more than one dimension:int m[5][9];m has the following appearance:Multidimensional Arrays•An element of m is accessed by writing m[i][j].•Example of multidimensional array use:#define NUM_ROWS 10#define NUM_COLS 10int m[NUM_ROWS][NUM_COLS], row, col;for (row = 0; row < NUM_ROWS; row++)for (col = 0; col < NUM_COLS; col++)if (row == col) m[row][col] = 1;else m[row][col] = 0;Initializing an Array•An array may be initialized at the point of definition. An array initializer is a list of expressions enclosed in braces:int a[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};•If an initializer is too short, the remaining elements of the array are given the value 0:int a[10] = {0};/* initial value of a is {0, 0, 0, 0, 0, 0, 0, 0, 0, 0} */An initializer cannot be empty nor can it be longer than the array it initializes.Initializing an Array•If an initializer is present, the length of the array may be omitted:int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};•Multidimensional arrays can be initialized:float matrix[5][3] = {{1.0, 1.0, 1.0}, {2.0, 2.0, 2.0}, {3.0, 3.0, 3.0}, {4.0, 4.0, 4.0}, {5.0, 5.0, 5.0}};Variable-Length Arrays (C99 Only)•In C99, the length of an array can be specified by a variable or other expression:int a[2*n+1];An array declared in this way is said to be a variable-length array.•Variable-length arrays are only allowed in functions (including
View Full Document