Arrays in C programming


Advertisements

Share



Learn C array declaration, initilization, accessing array elements, using array examples, 2-dimensional arrays, passing arrays to function.

What is array in C?

An array is a collection of variables of the same type. So instead of declaring individual variables one by one all can be declared once by using an array of same data type. For example instead of declaring 5 integers separately all can be declared as an integer array and can be accessed using an index.

An integer array contains couple of integers, a character array holds few characters and so on. Each array member is declared within single quote.

Array declaration, initialization

  • 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
  • One dimensional arrays do not require the dimension to be given if the array is to be completely initialized
  • Following are the array declaration examples.

    An integer array contains couple of integers, a character array holds few characters and so on. Each array member is declared within single quote. Also note in char carr[] = {'A','B','C','D','E'}; declaration we didn't give the number of elements the array can store. Compiler automatically computes this and allocates memory accordingly.

    
      int Arr1[5] = {1,2,3,4,5};  /* int array holding 5 integers */
      float Arr2[3] = {0.2,3.5,4.0}; /* float array holding 3 float elements */
      char carr[] = {'A','B','C','D','E'}; /* float array holding 5 char elements */
    

    Accessing elements, addresses

  • Elements of an array are accessed by specifying the index ( offset ) of the desired element within square [ ] brackets after the array name.
  • Array indices start at zero in C and go up to one less than the size of the array. For example, a five element array int Arr1[5] = {1,2,3,4,5};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.
  • Use loop to access all the elements of an array
  • You can get address of element i of an array using &array[i] or using array + i
  • The name of an array is nothing but the address of the first element of the array
  • To demonstrate the above features, let's write a small program as shown below

    
    #include "stdio.h"
    void main()
    {
      printf("=====Integer Array====\n");
      int iarr[5] = {0,1,2,3,4};
      int i;
      printf("Address of first element:%x,%x\n",iarr,&iarr[0]);
      for(i = 0;i < 5;i++)
      {
        printf("array %x and %x\n",&iarr[i],iarr + i);
        printf("array element:%d, %d\n",i,iarr[i]);
      }
      printf("=====Character Array====\n");
      char carr[5] = {'A','B','C','D','E'};
      for(i = 0;i < 5;i++)
      {
        printf("carr %x and %x\n",&carr[i],carr + i);
        printf("carr element:%d and %c\n",carr[i],carr[i]);
      }
    }
    
    Program output.
    =====================
    $ gcc prog.c
    $ ./a.out
    =====Integer Array====
    Address of first element:7eaef200,7eaef200
    iarr 7eaef200 and 7eaef200
    iarr element:0, 0
    iarr 7eaef204 and 7eaef204
    iarr element:1, 1
    iarr 7eaef208 and 7eaef208
    iarr element:2, 2
    iarr 7eaef20c and 7eaef20c
    iarr element:3, 3
    iarr 7eaef210 and 7eaef210
    iarr element:4, 4
    =====Character Array====
    carr 7eaef1f8 and 7eaef1f8
    carr element:65 and A
    carr 7eaef1f9 and 7eaef1f9
    carr element:66 and B
    carr 7eaef1fa and 7eaef1fa
    carr element:67 and C
    carr 7eaef1fb and 7eaef1fb
    carr element:68 and D
    carr 7eaef1fc and 7eaef1fc
    carr element:69 and E
    $
    

    In above program we have tried to access elements from int array[5]. Notice the addresses of array[0] is 7eac8200 which is same as name of array iarr. Also notice that the address of each successive element increases by 4 which means that integer takes 4bytes.

    Passing array to a function

    We can pass an array to a function. Also if we update any array element inside the function it will be reflected in the calling function as address of the array is passed to the function. This is demonstrated in the following example program.

    
    #include "stdio.h"
    #define SIZE 5
    int sumArr(int iarr[], int res[]);
    void main()
    {
      int iarr[SIZE] = {0,1,2,3,4};
      int sum[2] = {0,0};
      sum[0] = sumArr(iarr,sum);
      printf("Sum is:%d,%d\n", sum[0],sum[1]);
    }
    int sumArr(int iarr[],int res[])
    {
      int i, s = 0;
      for(i = 0;i < SIZE;i++)
      {
        s += iarr[i]; 
        res[1] += iarr[i];
      }
      return s;
    }
    
    Program output.
    =====================
    $ gcc prog.c
    $ ./a.out
    Sum is:10,10
    $
    

    In the above program we calculated the sum of all numbers in iarr in two ways. One way by returning the sum from function sumArr and another way by updating the 2nd element of sum array. Notice from the program output that both outputs are same.

    2-Dimensional arrays

  • 2-dimensional arrays are declared by providing 2 sets of square [ ] brackets after the variable name in the declaration statement.
  • For 2-dimensional arrays, the first dimension is commonly considered to be the number of rows, and the second dimension the number of columns.
  • Let's write a program to calculate the sum of all elements of a 2-dimensional array as shown below

    
    #include "stdio.h"
    int Sum2Arr(int a[2][3]);
    int main()
    {
      int res;
      int ar[2][3] = 
      {
        {1,2,3},
        {4,5,6}
      };
      res = Sum2Arr(ar);
      printf("The sum of 2d array integers:%d\n", res);
      return 0;
    }
    int Sum2Arr(int a[2][3])
    {
      int i,j,sum = 0;
      for(i = 0;i < 2;i++)
      {
        for(j = 0;j < 3;j++)
        {
          sum += a[i][j];
        }
      }
      return sum;
    }
    
    Program output.
    =====================
    $ gcc prog.c
    $ ./a.out
    The sum of 2d array integers:21
    $
    

    Exercises, Solutions

    High
    Medium
    Medium
    High
    Medium
    Low
    Medium

    Want to contribute a new article? Write and upload your article information .
    Share

     Articles

     C Programming

     Linux Software

     Search Code Snippets

     Popular C search examples

     Popular C search MCQs

    Glass Elite Apple iPhone 11 Pro (Case Friendly)

     Test your skills:online tests

     C Programming

     Python Programming

     Linux Software

     Quantitative Aptitude

     Embedded System Software