What are Arrays?
For understanding the arrays properly, let us consider the following program:
[c] void main(){
int a;
a = 5;
a = 10;
printf (“\na = %d”, a) ;
getch();
}
[/c]
This program will print the value of a as 10. Why so? Because when a value 10 is assigned to a, the earlier value of a, i.e. 5, is lost. Thus, ordinary variables are capable of holding only one value at a time. However, there are situations in which we would want to store more than one value at a time in a single variable.
Suppose we wish to arrange the percentage marks obtained by 50 students in decending order. In such a case we have two options to store these marks in memory:
- Construct 50 variables to store percentage marks obtained by 50 different students, i.e. each variable containing one student’s marks.
- Construct one variable (called array or subscripted variable) capable of storing or holding all the fifty values.
Obviously, the second alternative is better. Now a formal definition of an array: An array is a collective name given to a group of ‘similar quantities’. These similar quantities could be percentage marks of 100 students, or salaries of 1000 employees, or ages of 500 employees. What is important is that the quantities must be ‘similar’. Each member in the group is referred to by its position in the group. For example, assume the following group of numbers which represent age of five students.
[c] age[5]={18, 20, 25,30, 21};[/c] In C, the third number is referred as age|2]. This is because in C the counting of elements begins with 0 and not with 1. Thus, in this example age[3] refers to 30 and age[4] refers to 21. In general, the notation would be age[i], where, i can take a value 0, 1,2, 3, or 4, depending on the position of the element being referred. Here age is the subscripted variable (array), whereas i is its subscript.
Thus, an array is a collection of similar elements. These similar elements could be all ints, or all floats, or all chars, etc. All elements of any given array must be of the same type. i.e. we cannot have an array of 20 numbers, of which 10 are ints and 10 are floats.