ARRAYS: Introduction, working and advantages
Definition:
An array is a set of similar data types.
E.g. int marks[6];
--> In the above statement int is a data type of variable and marks is the name of the variable.
-->We can have 6 elements which are marks[0], marks[1], marks[2], marks[3], marks[4], marks[5].
-->So the subscript in bracket will take values from 0 to 5 and not 1 to 6.
--> [6] tells that there will be 6 elements of type int in our array.
--> This number is called the dimension of the array.
Consider the following program
/* Program for accepting marks of six subjects and calculating the average using array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int avg, sum=0,i;
int marks[6];//Declaration of array
//Accept marks of six subjects
printf("Enter marks of six subjects:");
for(i=0;i<6;i++)
{
scanf("%d",&marks[i]); //storing data in array
}
for(i=0;i<6;i++)
{
sum=sum + marks[i]; //reading stored data from array
}
avg=sum/6; //calculate average
printf("Average Marks:=%d",avg);
}
-->Once an array is declared the individual elements are referred with the help of subscript.
-->Subscript is the number in the bracket.
-->The subscript specifies the position of element in the array
-->All array elements are numbered starting from 0
E.g. marks[2]
-->Here, the subscript is 2 i.e the number in bracket
-->Marks[2] refers to the 3rd element and not the second element
--> So in the above program and with above input values
i.e. 90 80 90 80 90 95
marks[0]=90
marks[1]=80
marks[2]=90
marks[3]=80
marks[4]=90
marks[5]=95
-->This ability of using variables by using subscripts is what makes an array useful
-->Ordinary variables can hold only one value at a time
-->Suppose if we would have done the above program without using an array this would have been something like shown below:
/* Program for accepting marks of six subjects and calculating the average without using array*/
#include<stdio.h>
#include<conio.h>
void main()
{
int avg, sum=0,i;
int marks1,marks2,marks3,marks4,marks5,marks6;
//Accept marks of six subjects
printf("Enter marks of six subjects:");
scanf("%d %d %d %d %d %d",&marks1,&marks2,&marks3,&marks4,&marks5,&marks6);
sum=marks1 + marks2 + marks3 + marks4 + marks5 + marks6;
avg=sum/6;
printf("Average Marks:=%d",avg);
}
-->We can see in the previous version of the program we were handling only one variable that was an array variable
-->So handling array is much easier, it is clear from the programs that we have seen
-->So an array is a name given to group of ‘similar quantities’.
-->The importance of quantities being similar is that we can refer to them by its position in the group.
-->Array elements are stored at contiguous memory locations.
0 comments: