Array in c programming

Array in c...

  • An array is a collection of similar data under one variable name.
  • when we declare more variable under one name then we consider the array. 
  • In C Array is a collection of variables belongings to the same data type.You can store group of data of same data type in an array.Array might be belonging to any of the data typesArray size must be a constant value.Contiguous  memory locations are used to store array elements in memory.It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array.

examples;



  • int a[20];       // integer array
  • char b[20];    // character array
  • int a[];        //ok
  • int a[2] {1,4,3}  // Not ok 

Reading of Array;

          for(i=0;i<n;i++)
              scanf("%d",&a[i]);

Printing of Array;

           for(i=0;i<n;i++)

        there  are  two types of arrays



  1. One dimensional array
  2. Two dimensional array  
   

    1. One dimensional array
         A structured collection of components all of the same type, that is given a single name.Each                 component is accessed by an index that  indicates the component’s position within the                         collection. Array position is always started at 0 and goes up to one less then the size



      #include <stdio.h>
        int main()
         {
          int marks[10], i, n, sum = 0, average;
          printf("Enter n: ");
          scanf("%d", &n);
          for(i=0; i<n; ++i)
         {
          printf("Enter number%d: ",i+1);
          scanf("%d", &marks[i]);
          sum += marks[i];
          }
         average = sum/n;

        printf("Average = %d", average);

        return 0;
         }
  • Enter n: 5
  • Enter number1: 45
  • Enter number2: 35
  • Enter number3: 38
  • Enter number4: 31
  • Enter number5: 49

      2.  Two dimensional 
  •       Two dimensional array are those type of array, which has finite number of rows and finite number of columns. 
  • The declaration form of 2-dimensional array is
      Data_type    Array_name [row size][column size];

  • The type may be any valid type supported by C.
  • The rule for giving the array name is same as the ordinary variable.
  • The row size and column size should be an individual constant.
        The following declares a two-dimensional 3 by 3 array of integers and sets the first and last                   elements to be 20.

int matrix [3][3];
matrix[0][0] = 20;
matrix[2][2] = 20;
   



No comments:

Post a Comment