Tuesday 1 October 2013

Array in C

Function                                                                                                                         String



Array:- Array is used to store the elements of same datatype in continuous memory location.
collection of element of same datatype. if you want to store the details of 100 employee
and you declared 100 variables which takes more time and increase the complexity of the program.
so we can do this through array which makes its easier.

Two types of array:-
Single dimensional
Multi dimensional

Single Dimensional array:-

declaration:- int a[10];

where int -datatype means array store element of int type only.
  a -  name of the array.
10 - size of the array.it can only store 10 elements.

if you declare
int a[3];
it means :
this is the single dimensional array.
index starts from  0  .
where a[0] represents the first element of array.
initializing array:

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

Ex:-
#include<stdio.h>
void main()
{
int a[5],i;
for(i=0;i<5;i++)
{
printf("enter the value:");
scanf("%d",&a[i]);
}
for(i=0;i<5;i++)
{
printf("%d",a[i]);
}
}

by using first for loop we are inserting the value into the array.
by using second for loop we are printing the elements of array.

we can also access the value at particular index

printf("%d",a[2]);
it prints the third element of array.

Multi Dimensional Array:- The array which contains more than one dimension is known as multi dimensional array.

declaration:- int a[2][2];

         
it contains 2 row 2 column.

Ex:-
#include<stdio.h>
void main()
{
int a[2][2] , i , j;
for(i=0;i<2;i++)
 {
   for(j=0;j<2;j++)
    {
      printf("enter the value:");
      scanf("%d",&a[i][j]);
     }
  }
 for(i=0;i<5;i++)
   {
     for(j=0;j<2;j++)
     {
        printf("%d",a[i][j]);
     }
   }
 }

by using first for loop we are inserting the value into the array.
by using second for loop we are printing the elements of array.


Array with Function:- in this simply we pass the array to the function as a argument.

Ex:-
#include<stdio.h>
int sum(int a[]);
void main()
{
int a[4]={1,2,3,4};
int s;
s=sum(a);  // passing the name of array.
printf("%d",s);
}
int sum(int a[])
{
int i,j;
for(i=0;i<4;i++)
{
j=j+a[i];
}
return j;
}

output :-10

it returns the sum to s.







No comments :

Post a Comment