Module 4: Arrays

Module 4 - Topic 1 : Arrays


Overview

  • An array is a collection of data items, all of the same type, accessed using a common name.

  • A one-dimensional array is like a list;  A two dimensional array is like a table;  The C++ language places no limits on the number of dimensions in an array, though specific implementations may.

  • Some texts refer to one-dimensional arrays as vectors, two-dimensional arrays as matrices, and use the general term arrays when the number of dimensions is unspecified or unimportant.


C arrays


An array is a variable that can store multiple values. For example, if you want to store 100 integers, you can create an array for it.

int data[100];

How to declare an array?

dataType arrayName[arraySize];

For example,

float mark[5];

Here, we declared an array, mark, of floating-point type. And its size is 5. Meaning, it can hold 5 floating-point values.

It's important to note that the size and type of an array cannot be changed once it is declared.


Declaring Arrays

  • Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array.

  • Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.

  • Dimensions used when declaring arrays in C++ must be positive integral constants or constant expressions

  • Examples:

        int i, j, intArray[ 10 ], number;
        float floatArray[ 1000 ];
        int tableArray[ 3 ][ 5 ];      /* 3 rows by 5 columns */
        
        const int NROWS = 100;      // ( Old code would use #define NROWS 100 )
        const int NCOLS = 200;      // ( Old code would use #define NCOLS 200 )
        float matrix[ NROWS ][ NCOLS ];

Initializing Arrays

  • Arrays may be initialized when they are declared, just as any other variables.

  • Place the initialization data in curly {} braces following the equals sign.  Note the use of commas in the examples below.

  • An array may be partially initialized, by providing fewer data items than the size of the array.  The remaining array elements will be automatically initialized to zero.

  • If an array is to be completely initialized, the dimension of the array is not required.  The compiler will automatically size the array to fit the initialized data.  ( Variation:  Multidimensional arrays - see below. )

  • Examples:

        int i =  5, intArray[6] = { 1, 2, 3, 4, 5, 6 }, k;
        float sum  = 0.0, floatArray[100] = { 1.10, 5.50, 20.20 };
        double  piFractions[] = { 3.141592654, 1.570796327, 0.785398163 };

Using Arrays

  • Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name.

  • Array subscripts must be of integer type.  ( int, long int, char, etc. )

  • VERY IMPORTANT: Array indices start at zero in C++, and go to one less than the size of the array.  For example, a five element array will have indices zero through four.  This is because the index in C++ is actually an offset from the beginning of the array.  ( The first element is at the beginning of the array, and hence has zero offset. )

  • Landmine:  The most common mistake when working with arrays in C++ is forgetting that indices start at zero and stop one less than the array size.

  • Arrays are commonly used in conjunction with loops, in order to perform the same calculations on all ( or some part ) of  the data items in the array.

Sample Programs Using 1-D Arrays

  • The first sample program uses loops and arrays to calculate the first twenty Fibonacci numbers.  Fibonacci numbers are used to determine the sample points used in certain optimization methods.

        /* Program to calculate the first 20 Fibonacci numbers. */

       #include <stdio.h>

        int main() {         

            int i, fibonacci[ 20 ];

            fibonacci[ 0 ] = 0;

            fibonacci[ 1 ] = 1;

        

            for( i = 2; i < 20; i++ ){

                fibonacci[ i ] = fibonacci[ i - 2 ] + fibonacci[ i - 1 ];}

              

            for( i = 0; i < 20; i++ ){

                printf( "Fibonacci[ %d ] = %d\n", i, fibonacci[ i ] );}

        } /* End of sample program to calculate Fibonacci numbers */ 

  • Exercise: What is the output of the following program:

        /* Sample Program Using Arrays */
        
        #include <stdio.h> 
        
        int main() {
        
            int numbers[ 10 ];
            int i, index = 2;
            
            for( i = 0; i < 10; i++ ) 
                numbers[ i ] = i * 10;
            
            numbers[ 8 ] = 25;
            numbers[ 5 ] = numbers[ 9 ] / 3;
            numbers[ 4 ] += numbers[ 2 ] / numbers[ 1 ];
            numbers[ index ] = 5;
            ++numbers[ index ];
            numbers[ numbers[ index++ ] ] = 100;
            numbers[ index ] = numbers[ numbers[ index + 1 ] / 7 ]--;
            
            for( index = 0; index < 10; index++ )
                printf( "numbers[%d] = %d\n", index, numbers[index] );
            
        } /* End of second sample program */

Access Array Elements

You can access elements of an array by indices.

Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on.

C Array declaration


Few keynotes:
  • Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.

  • If the size of an array is n, to access the last element, the n-1 index is used. In this example, mark[4]


How to initialize an array?

It is possible to initialize an array during declaration. For example,

int mark[5] = {19, 10, 8, 17, 9};

You can also initialize an array like this.

int mark[] = {19, 10, 8, 17, 9};

Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements.

Initialize an array in C programming

Here,

mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9

Change Value of Array elements

int mark[5] = {19, 10, 8, 17, 9}

// make the value of the third element to -1
mark[2] = -1;

// make the value of the fifth element to 0
mark[4] = 0;

Input and Output Array Elements

Here's how you can take input from the user and store it in an array element.

// take input and store it in the 3rd element
​scanf("%d", &mark[2]);

// take input and store it in the ith element
scanf("%d", &mark[i-1]);

Here's how you can print an individual element of an array.

// print the first element of the array
printf("%d", mark[0]);

// print the third element of the array
printf("%d", mark[2]);

// print ith element of the array
printf("%d", mark[i-1]);

Example 1: Array Input/Output

// Program to take 5 values from the user and store them in an array
// Print the elements stored in the array
#include <stdio.h>
int main() {
  int values[5];

  printf("Enter 5 integers: ");

  // taking input and storing it in an array
  for(int i = 0; i < 5; ++i) {
     scanf("%d", &values[i]);
  }

  printf("Displaying integers: ");

  // printing elements of an array
  for(int i = 0; i < 5; ++i) {
     printf("%d\n", values[i]);
  }
  return 0;
}

Output

Enter 5 integers: 1
-3
34
0
3
Displaying integers: 1
-3
34
0
3

Here, we have used a for loop to take 5 inputs from the user and store them in an array. Then, using another for loop, these elements are displayed on the screen.


📚Summary 4.1

  • An array is a collection of data items, all of the same type, accessed using a common name.

  • A one-dimensional array is like a list.

  • Array variables are declared identically to variables of their data type, except that the variable name is followed by one pair of square [ ] brackets for each dimension of the array.

  • Uninitialized arrays must have the dimensions of their rows, columns, etc. listed within the square brackets.

  • Dimensions used when declaring arrays in C must be positive integral constants or constant expressions.


  • Module 4 - Topic 2 : Multidimensional Arrays


    Multidimensional Arrays

    • Multi-dimensional arrays are declared by providing more than one set of square [ ] brackets after the variable name in the declaration statement.

    • One dimensional arrays do not require the dimension to be given if the array is to be completely initialized.  By analogy, multi-dimensional arrays do not require the first dimension to be given if the array is to be completely initialized.  All dimensions after the first must be given in any case.

    • For two dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second dimension the number of  columns.  We will use this convention when discussing two dimensional arrays.

    • Two dimensional arrays are considered by C/C++ to be an array of ( single dimensional arrays ).  For example, "int numbers[ 5 ][ 6 ]"  would refer to a single dimensional array of 5 elements, wherein each element is a single dimensional array of 6 integers.  By extension, "int numbers[ 12 ][ 5 ][ 6 ]" would refer to an array of twelve elements, each of which is a two dimensional array, and so on.

    • Another way of looking at this is that C++ stores two dimensional arrays by rows, with all elements of a row being stored together as a single unit.  Knowing this can sometimes lead to more efficient programs. 

    • Multidimensional arrays may be completely initialized by listing all data elements within a single pair of curly {} braces, as with single dimensional arrays.

    • It is better programming practice to enclose each row within a separate subset of curly {} braces, to make the program more readable.  This is required if any row other than the last is to be partially initialized.  When subsets of braces are used, the last item within braces is not followed by a comma, but the subsets are themselves separated by commas.

    • Multidimensional arrays may be partially initialized by not providing complete initialization data.  Individual rows of a multidimensional array may be partially initialized, provided that subset braces are used.

    • Individual data items in a multidimensional array are accessed by fully qualifying an array element.  Alternatively, a smaller dimensional array may be accessed by partially qualifying the array name.  For example, if  "data" has been declared as a three dimensional array of floats, then data[ 1 ][ 2 ][ 5 ] would refer to a float, data[ 1 ][ 2 ] would refer to a one-dimensional array of floats, and data[ 1 ] would refer to a two-dimensional array of floats.  The reasons for this and the incentive to do this relate to memory-management issues that are beyond the scope of these notes.


    C++ Multidimensional Arrays

    In C++ programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example,
    float x[3][4];

    Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 rows and each row has 4 columns.

     

    Two dimensional array in C programming

     

    Similarly, you can declare a three-dimensional (3d) array. For example,

    float y[2][4][3];

    Here, the array y can hold 24 elements.


    Initializing a multidimensional array

    Here is how you can initialize two-dimensional and three-dimensional arrays:


    Initialization of a 2d array

    // Different ways to initialize two-dimensional array
    
    int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
             
    int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
                    
    int c[2][3] = {1, 3, 0, -1, 5, 9};

    Initialization of a 3d array

    You can initialize a three-dimensional array in a similar way like a two-dimensional array. Here's an example,

    int test[2][3][4] = {
        {{3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2}},
        {{13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9}}};

     📝To continue with the lesson, I have provided below the embedded the PDF Presentation. You may also download the file via Google drive. Please click the provided link: Module 4: Arrays - Topic 2 : Multidimensional ArraysLinks to an external site..

     


     

    C programming language allows multidimensional arrays. Here is the general form of a multidimensional array declaration −

    data_type Array_Name[size1][size2]...[sizeN];
    

    For example, the following declaration creates a three dimensional integer array −

    int threedim[5][10][4];
    

    Two-dimensional Arrays

    The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. To declare a two-dimensional integer array of size [x][y], you would write something as follows −

    type arrayName [ x ][ y ];
    

    Where type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table which will have x number of rows and y number of columns. A two-dimensional array a, which contains three rows and four columns can be shown as follows −

    Thus, every element in the array a is identified by an element name of the form a[ i ][ j ], where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify each element in 'a'.


    Initializing Two-Dimensional Arrays

    Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array with 3 rows and each row has 4 columns.

    int a[3][4] = {  
       {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
       {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
       {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
    };

    The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to the previous example −

    int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};
    

    Accessing Two-Dimensional Array Elements

    An element in a two-dimensional array is accessed by using the subscripts, i.e., row index and column index of the array. For example −

    int val = a[2][3];
    

    The above statement will take the 4th element from the 3rd row of the array. You can verify it in the above figure. Let us check the following program where we have used a nested loop to handle a two-dimensional array.


    #include <stdio.h>
     
    int main () {
    
       /* an array with 5 rows and 2 columns*/
       int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
       int i, j;
     
       /* output each array element's value */
       for ( i = 0; i < 5; i++ ) {
    
          for ( j = 0; j < 2; j++ ) {
             printf("a[%d][%d] = %d\n", i,j, a[i][j] );
          }
       }
       
       return 0;
    }

    When the above code is compiled and executed, it produces the following result −

    a[0][0]: 0
    a[0][1]: 0
    a[1][0]: 1
    a[1][1]: 2
    a[2][0]: 2
    a[2][1]: 4
    a[3][0]: 3
    a[3][1]: 6
    a[4][0]: 4
    a[4][1]: 8
    

    As explained above, you can have arrays with any number of dimensions, although it is likely that most of the arrays you create will be of one or two dimensions.


    Sample 1

    #include <stdio.h>

    int main(){

                    int NumX[2][4]= {{1,2,3,4},{1,2,3,4}};

                    int x,y;

                    for(x=0;x<2;x++){

                                    for(y=0;y<4;y++){

                                    printf("%d",NumX[x][y]);

                                    }

                                    printf("\n");

                    }

                    return 0;

    }

Summary 4.2

  • A multi-dimensional array is an array that has more than one dimension.

  • It is an array of arrays; an array that has multiple levels.

  • The simplest multi-dimensional array is the 2D array, or two-dimensional array.

  • It's technically an array of arrays, as you will see in the code.

  • A 2D array is also called a matrix, or a table of rows and columns.