Arrays

Declaring an array

  1. An array is a variable with multiple memory cells.
  2. The number of cells are determined when it is declared.
    Example:
    double x[8];
    

  3. The above declaration is a variable called x that contains eight elements. The elements are referenced as x[0] through x[7].

Initializing an array

  1. An array can be given initial values.
    Example:
    double x[] = {1.3, 6.0, 4.1, 3.7, 0.0, 1.0, 3.3, 7.43};
    

  2. It isn't necessary to explicitly give the array size, since that can be determined from the init list.

An example program

  1. The following program will use arrays to keep track of grades in a class.
    Example:
    #include <stdio.h>
    #include <math.h>
    #define NUM_STU 5 /* 5 students in the class */
    
    
    /* Two arrays, one for student id, and one for 
       student grade */
    
    int student_id[NUM_STU] = {123, 223, 326, 117, 326};
    int student_gr[NUM_STU] = {84, 74, 90, 100, 70};
    
    
    
    int main() {
    
    	int i, hi, lo, sum;
    	double avg;
    
    	hi = student_gr[0];
    	lo = student_gr[0];
    	sum = 0;
    
    
        /* Let's print the grades to the screen */
    
    	printf("id\tgrade\n");
    
    	for (i = 0; i < NUM_STU; i++) {
    
    	    printf("%d\t%d\n",student_id[i], student_gr[i]);
    
    	    if(hi < student_gr[i])
    		hi = student_gr[i];
    
    	    if(lo > student_gr[i])
    		lo = student_gr[i];
    
    	    sum += student_gr[i];
    
    	}
    
    	printf("\nThe highest grade: %d", hi);
    	printf("\nThe lowest grade: %d", lo);
    
            printf("\nThe sum of the grades: %d", sum);
    
    	avg = sum / NUM_STU;
    
    	printf("\nThe average grade: %f\n\n", avg);
    
    
    	return 0;
    
    }
    
    Source File | DOS Executable (run from DOS prompt)

  2. The output of this program looks like this:
    id      grade
    123     84
    223     74
    326     90
    117     100
    326     70
    
    The highest grade: 100
    The lowest grade: 70
    The sum of the grades: 418
    The average grade: 83.000000
    
    

Multidimensional arrays

  1. An array can have 2 or more dimensions
    Example:
    double x[8][3];
    

  2. The above declares an 8 x 3 array, or an array of 24 elements.
  3. A multidimensional array can be initialized as seen below:
    Example:
    int x[3][3] = { {1, 4, 3}, {4, 8, 2}, {7, 9, 11} };;