Chapter 3 Arrays




A array is a group of related data items that share a common name.
One - Dimensional Arrays :
A list of items can be given one variable name using only one subscript and such variable is called singled subscripted variable or a one-dimensional array. The subscript(index) begin with number 0 (zero)
The general form of one-d array declaration is :
Type array_name [size];
Ex :
int x [5];
x[0]
 






     
x[1]
x[2]
x[3]
x[4]






The general form of initialization of array :
int x[5] = {1,2,3,4,5};
x[0]
1
2
3
4
5
x[1]
x[2]
x[3]
x[4]

 /* To find out the sum of given 10  numbers. using arrays */
#include<stdio.h>
#include<conio.h>
main()
{
int a[10],i,sum=0;
clrscr();
for(i=0;i<10;i++)
{
printf("\n enter the number : ");
scanf("%d",&a[i]);
sum = sum+a[i];
}
printf("\n sum is : %d",sum);
getch();
Two - Dimensional Arrays :
There will be situations where a table of values will have to be stored. The general form of declared two-dimensional array :
type array_name [row] [col];
Ex :
int a[3][4];
a[3][4]0123cols
0
1
2
rows
 initialization of 2-D array :
int a[3][4] = { {1,2,3,4},{5,6,7,8},{9,1,2,3}};
a[3][4]0123cols
0
1234
5678
9123
1
2
rows
 /* Add two 2-D array */

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
int a[3][3],b[3][3],c[3][3],i,j;
printf("\n enter matrix a:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);

printf("\n enter matrix b:\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\n sum of given matrix is :\n");
for (i=0;i<3;i++)
for(j=0;j<3;j++)
printf(" %3d",c[i][j]);
printf("\n");
}
getch();
}


Multi - Dimensional Arrays :
c allows arrays of three or more dimensions. the exact limit is determined by compiler. The general form of a multi dimensional array is
type array_name [s1][s2][s3]...[sm];