Featured Post

Thursday, October 13, 2016

Arrays in C



Array:
    An array is a collection of similar data items. For example group of integer data items is called integer array. Similarly float array is group of float data items.

Consider a scenario of saving 50 roll numbers in a class. We need 50 variables to store 50 roll number ( numbers) in memory. Using arrays we can save 50 numbers in memory using a single variable name for example a.

   int  a[50]; /* array declaration. "a" occupies 50*2=100 bytes of memory*/
   /*first number is referred in memory as a[0], second number in memory is referred as a[1] and so on and last number in memory is referred as a[49].*/

Initialization of array elements :

Compile time initialization:
             
                  int a[6]={10,21,32,34,45,67};
                  
               which means a[0]=10, a[1]=21,a[2]=32,a[3]=34,a[4]=45,a[5]=67.

/*Write a C program to read 5 numbers and display the same 10 number on the screen*?

main()
{
   int a[5]={10,20,30,40,50};
  printf("%d\t%d\t%d\t%d\t%d",a[0],a[1],a[2],a[3],a[4]);
}
output:
               10    20    30   40    50


Run time initialization:
          Allocating the values to array member at run time is called run time initialization. Using scanf function we can give values to an array at run time.


/*Write a C program to array values from the keyboard and display the same on the screen*/

main()
{
   int a[100],i,n;
   printf("\n enter your range");
   scanf("%d",&n);
   for(i=0;i<n;i++)
   {
     scanf(%d",&a[i]);
   }
  for(i=0;i<n;i++)
  {
    printf("%d \t ", a[i]);
  }
}

OUTPUT
Enter your range 6
10
23
32
34
45
67
10   23    32   34   45   67

/*Write a C program to find the sum and total of 6 subjects*/

main()
{
  int a[6],sum=0,i;
  float avg;
  printf("\n enter your six subject marks");
  for(i=0;i<6;i++)
  {
     scanf(%d",&a[i]);
  }
 for(i=0;i<6;i++)
 {
   sum=sum+a[i];
  }
  avg=total/6.0;
printf("total and average of six subjects are %d \t %f", sum, avg);
}

OUTPUT:
enter your six subject marks

40
50
40
40
40
30

total and average of six subjects are 240    40







Arrays in c, initialization of arrays, run time initialization, two dimensional arrays, linear search, binary search







No comments:

Post a Comment