Array is a variable that
represents a collection of identical objects , that means we can store a group
of variables of same data type and name together
Do you remember the strings , yes
that was a character array , but now we will see integer array
Each member of an array is
referred by a index value starting with 0 and the last element of a array is an
null character that is \0
The above figure shows a array of
elements of size 20 , but remember that since the last position is occupied by
a null character so the actual size of the array is 19
As said we can have array of
integers or array of characters also called strings
Syntax for array is
Data_type
array_name [size of array];
We can accept values for every
array element one by one but that is not how it is done , instead we use a loop
(for loop ) to enter and to print the values of an array , but it is possible
to do one by one if needed
main()
{
int array[5];
int i;
for(i=0;i<5;i++)
{
printf("Enter number fo position %d \n",i+1);
scanf("%d",&array[i]);
}
for(i=0;i<5;i++)
{
printf(" Array Element in %d is ..... %d\n",i+1,array[i]);
}
getch();
The above program accepts values
for the array “int arrya” , loops it in
a for loop that runs from 0 to 4 and in each time changes the index of the
array “array[i]” to save the values at different positions and in the next for
loop prints the array elements one by one
Multi
dimensional Array
Sine now we were only seeing
array that can store values like the compartments of a train each one having
one value but now we will see multi dimensional array , think it of like a stack
of train on one another
So multidimensional array looks
like
Data_type
array_name [column size] [row size];
So if we have an array of [2][20]
It will look like this
We can use these kind of array to
form a grid but for now let us print time table from 1 to 10 using multi
dimensional array and for loop
main()
{
int i,j;
int
array[10][10];
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
array[i][j] = (i+1)*(j+1);
}
}
for(i=0;i<10;i++)
{
for(j=0;j<10;j++)
{
printf("%3d ",array[i][j]);
}
printf("\n");
}
getch();
}
This programs just display the
times table from 1 to 20
No comments:
Post a Comment