• Main Menu
  • Arrays


    An array is a collection of C or C++ data elements or objects of the same type. Individual elements of an array are referenced using one or more integer indices. A one-dimensional array is defined with a statement such as double vector[50]. This defines (and allocates space for) 50 variables of type double that are contiguously located in storage. This means that 50 different values can be stored without having to initialize 50 different variables, each one with a different identifier. Instead,  an array can store 50 different values of the same type under a single identifier.

    Arr[0] Arr[1] Arr[2] Arr[3] Arr[4]

    The above figure shows an array of 5 different integer elements stored in contiguous memory locations. The above array is initialized as int Arr[5]. These elements are indexed from 0 to 4, since in an array the first index is always 0 (zero), independent of its total length. An array is initialized in the same way an ordinary variable is declared and it must also be declared before it is used. A typical declaration for an array in C++ is:

    datatype arrayname[array_length] ; 
    //Eg: 
    char firstname[100] ;

    A datatype is a format used to depict the values of a data element (eg: int, char, float). Datatypes can also be user defined. An arrayname is the name of the array. In the above example, it is firstname. The array_length is the number of elements the array can store in memory.

    What are Array Subscripts ?

    Individual elements of an array are referenced by a subscript.

    vector[0] = vector[1] = 5.0 ;

    Array subscripts are non-negative integers or expressions that evaluate to a non-negative integer value. For an array with N number of elements, array subscripts will range from 0 to N-1 and not from 1 to N. Memory space, for the array elements, is allocated contiguously in computer’s memory, beginning with the 0th element: vector[0], vector[1], vector[2] ...vector[49].

    How to initialize an array?

    Arrays can be initialized by a list of constant values:

    double vector[3] = {0.0, 1.0, 2.0} ;
    vector[0] vector[1] vector[2]
    0.0 1.0 2.0

    The number of elements in an array can be inferred by the compiler from the number of initializing constants:

    int myvector[] = {0,1,2,3,4,5,6} ;

    The above example indicates an array with seven elements.

    Static arrays are initialized when the program is loaded and the values are initially assigned zero by default. Arrays are automatically initialized when they are defined and do not have a default initial value (unless they are arrays of objects).

    Arrays can also be initialized in a control loop:

    int myarray[5]; 
    for(int i=0 ; i<=4 ; i++) 
    {  
        cout<<”Enter the ”<< i+1 <<” element:”;  
        cin>>myarray[i]; 
    }

    The above code allows the user to initialize the array with values accepted from the user.

    #include <iostream.h>
    void main()
    {
        int arr[5] = (0, 0, 0, 0, 0);
        for(int i=0 ; i<=4 ; i++) 
        {  
            cout<<”enter the ”<< i+1 <<” element:”;  
            cin>>arr[i]; 
        }
        cout <<"\n";
        cout << "-----------the array element---------- \n" ;
        for(int j=0 ; j<=4 ; j++) 
        {  
            cout<<"\t"<<arr[j];
        }
    }

    Output:

    enter the 1 element :5
    enter the 2 element :67
    enter the 3 element :89
    enter the 4 element :55
    enter the 5 element :44
    
    -----------the array element----------
        5       67      89      55      44

    The above shown figure is the code which allows the user to input 5 array elements in the arr array of type integer and then print the same values on the screen.

    How to access the values of an array?

    At any point in a program, in where an array is visible, we can access the value of any of its element individually as if it was a normal variable, thus allowing to read and modify its value. The format is as simple as:

    arrayname[index] ;

    The following figure shows an array of 5 elements by the name arr, of the type integer, the elements of which will be accessed in a method as described above

    arr[0] arr[1] arr[2] arr[3] arr[4]
    256 125 72 222 569

    A value of 72 can be initialized to the 3rd element of the array by the following method,

    arr[2] = 72 ;

    Similarly the value of one of the element can be stored in another variable by,

    int a = arr[2] ;

    This gives variable a the value of arr[2] which is 72. The 3rd element of the array is accessed using arr[2] since the array index starts from 0 to N-1, which is 4 in the above case. If we try to access arr[5], the range of the array would exceed beyong the allowed limit, which would result into an runtime error.

    In C++ it is syntactically correct to exceed the valid range of indices of an array. This can create problems, since accessing out-of-range elements do not cause compilation errors but can cause runtime errors. The reason why this is allowed would be clear with the study of pointers.

    #include <iostream.h>
    int billy[] = (1, 2, 3, 4, 5);
    int n, result=0;
    void main()
    {
    
        for(n=0 ; n< 5 ; n++) 
        {  
            result += billy[n];
        }
        cout << "The result of the following Array is   :"<< result ;
    }

    Output:

    The result of the following Array is   :15

    What are multi-dimensional arrays?

    A two-dimensional array is an array in which each element is itself an array. We have discussed one-dimensional arrays, now let’s expand our horizon and talk about N-dimensional arrays. Multi-dimensional arrays are also known as ‘array of arrays’.

    The following figure shows a 2-dimensional array of integer elements,

    int Arr[2][5] ;
    Arr[0][0] Arr[0][1] Arr[0][2] Arr[0][3] Arr[0][4]
    Arr[1][0] Arr[1][1] Arr[1][2] Arr[1][3] Arr[1][4]

    A 2-dimensional array is initialized as:

    datatype arrayname[rows][columns] ;

    A datatype is a format used to depict the values of a data element (eg: int, char, float). Datatypes can also be user defined. An arrayname is the name of the array. The rows and columns are the number of elements (number of rows and columns) the array can store in memory. Unlike a bi-dimensional array, a multi-dimensional array is not limited to two indices (i.e., two dimensions). It can contain as many indices as needed.

    int arr[4][5][7][8] ;

    The above declaration is of a four-dimensional array, but these type of arrays are difficult to visualize.

    Although a single-dimensional array can be used in most of the problems, at times there would be certain scenarios which would require a multi-dimensional array like matrix manipulation problems.

    The program below shows a two-dimensional array whose values are accepted from the user and then displayed. The summation of all the values of the array is calculated and displayed as output.

    #include <iostream.h>
    cons int M = 3; //number of rows
    cons int N = 4; //number of column
    void main()
    {
        int a[M][N], i, j, sum = 0;
        for(i = 0; i < M; ++i) // fill the array
        {
            for(j = 0; j < N; ++j) 
            {
                a[i][j] = i + j;
            }
        }
        for(i = 0; i < M; ++i) // print array
        {
            for(j = 0; j < N; ++j) 
            {
                cout << "a[" << i << "] [" << j << "] = " << a[i][j] << '\t';
            }
        }
        for(i = 0; i < M; ++i) // sum the array
        {
            for(j = 0; j < N; ++j) 
            {
                sum += a[i][j];
            }
        }
        cout << "\n sum = " << sum << endl;
    }

    Output:

    a[0][0] = 0     a[0][1] = 1     a[0][2] = 2     a[0][3] = 3     
    a[1][0] = 1     a[1][1] = 2     a[1][2] = 3     a[1][3] = 4     
    a[2][0] = 2     a[2][1] = 3     a[2][2] = 4     a[2][3] = 5 
    sum = 30

    Got Something To Say:

    Your email address will not be published. Required fields are marked *

    C
    } 234 queries in 0.476 seconds.