Site pages
Current course
Participants
General
Module - 1 C Language Fundamentals
Module-2 Decision Making, Looping and Functions
Module 3 – Array, Structure and Pointers
Module-4 Data Structures
22 March - 28 March
Module 6. User define Functions, String Functions,...
Module 7. Passing arguments and returning values
Module 8. Recursion, scope and visibility of a var...
Module 9. Structures and union.
Module- 10 Pointers, Stacks, Push/Pop operations.
Lesson-11 Array
11.1 INTRODUCTION
An array is a collection of data storage locations, each having the same data type and the same name. Each storage location in an array is called an array element. Why do you need arrays in your programs? let us consider the following program:
void main( )
{
int x ;
x = 5 ;
x = 10 ;
printf ( "\nx = %d", x ) ;
}
No doubt, this program will print the value of x as 10. Why so? Because when a value 10 is assigned to x, the earlier value of x, i.e. 5, is lost. Thus, ordinary variables (the ones which we have used so far) are capable of holding only one value at a time (as in the above example). However, there are situations in which we would want to store more than one value at a time in a single variable.
For example, suppose we wish to arrange the percentage marks obtained by 100 students in ascending order. In such a case we have two options to store these marks in memory:
Construct 100 variables to store percentage marks obtained by 100 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 hundred values.
Obviously, the second alternative is better. A simple reason for this is, it would be much easier to handle one variable than handling 100 different variables. Moreover, there are certain logics that cannot be dealt with, without the use of an array. 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 300 employees, or ages of 50 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 percentage marks obtained by five students.
per = { 48, 88, 34, 23, 96 }
If we want to refer to the second number of the group, the usual notation used is per2. Similarly, the fourth number of the group is referred as per4. However, in C, the fourth number is referred as per[3]. This is because in C the counting of elements begins with 0 and not with 1. Thus, in this example per[3] refers to 23 and per[4] refers to 96. In general, the notation would be per[i], where, i can take a value 0, 1, 2, 3, or 4, depending on the position of the element being referred. Here per 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. Usually, the array of characters is called a ‘string’, whereas an array of ints or floats is called simply an array. Remember that all elements of any given array must be of the same type. i.e. we cannot have an array of 10 numbers, of which 5 are ints and 5 are floats.
Arrays can be classified into two different categories:
Single dimensional arrays
Multi dimensional arrays
11.2 A Program Using Single Dimensional Array
A single-dimensional array has only a single subscript. A subscript is a number in brackets that follows an array's name. This number can identify the number of individual elements in the array.Let us try to write a program to find average marks obtained by a class of 30 students in a test.
void main( )
{
int avg, sum = 0 ;
int i ;
int marks[30] ; /* array declaration */
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ; /* store data in array */
}
for ( i = 0 ; i <= 29 ; i++ )
{
sum = sum + marks[i] ; /* read data from an array*/
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
}
There is a lot of new material in this program, so let us take it apart slowly.
11.2.1 Array Declaration
To begin with, like other variables an array needs to be declared so that the compiler will know what kind of an array and how large an array we want. In our program we have done this with the statement:
int marks[30] ;
Here, int specifies the type of the variable, just as it does with ordinary variables and the word marks specifies the name of the variable. The [30] however is new. The number 30 tells how many elements of the type int will be in our array. The bracket ( [ ] ) tells the compiler that we are dealing with a single dimensional array.
Accessing Elements of an Array
Once an array is declared, let us see how individual elements in the array can be referred. This is done with subscript, the number in the brackets following the array name. This number specifies the element’s position in the array. All the array elements are numbered, starting with 0. Thus, marks[2] is not the second element of the array, but the third. In our program we are using the variable i as a subscript to refer to various elements of the array. This variable can take different values and hence can refer to the different elements in the array in turn. This ability to use variables as subscripts is what makes arrays so useful.
11.2.2 Entering Data into an Array
Here is the section of code that places data into an array:
for ( i = 0 ; i <= 29 ; i++ )
{
printf ( "\nEnter marks " ) ;
scanf ( "%d", &marks[i] ) ;
}
The for loop causes the process of asking for and receiving a student’s marks from the user to be repeated 30 times. The first time through the loop, i has a value 0, so the scanf( ) function will cause the value typed to be stored in the array element marks[0], the first element of the array. This process will be repeated until i becomes 29. This is last time through the loop, which is a good thing, because there is no array element like marks[30].
In scanf( ) function, we have used the “address of” operator (&) on the element marks[i] of the array, just as we have used it earlier on other variables (&rate, for example). In so doing, we are passing the address of this particular array element to the scanf( ) function, rather than its value; which is what scanf( ) requires.
11.2.3 Reading Data from an Array
The balance of the program reads the data back out of the array and uses it to calculate the average. The for loop is much the same, but now the body of the loop causes each student’s marks to be added to a running total stored in a variable called sum. When all the marks have been added up, the result is divided by 30, the number of students, to get the average.
for ( i = 0 ; i <= 29 ; i++ )
{
sum = sum + marks[i] ;
}
avg = sum / 30 ;
printf ( "\nAverage marks = %d", avg ) ;
11.2.4 More on Arrays
So far we have used arrays that did not have any values in them to begin with. We managed to Array is a very popular data type with C programmers. This is because of the convenience with which arrays lend themselves to programming. The features which make arrays so convenient to program would be discussed below, along with the possible pitfalls in using them.
Array Initialisation store values in them during program execution. Let us now see how to initialize an array while declaring it. Following are a few examples that demonstrate this.
int num[6] = { 2, 4, 12, 5, 45, 5 } ;
int n[ ] = { 2, 4, 12, 5, 45, 5 } ;
float press[ ] = { 12.3, 34.2 -23.4, -11.3 } ;
Note the following points carefully:
Till the array elements are not given any specific values, they are supposed to contain garbage values.
If the array is initialised where it is declared, mentioning the dimension of the array is optional as in the 2nd example above.
11.2.5 Array Elements in Memory
Consider the following array declaration:
int arr[8] ;
What happens in memory when we make this declaration? 16 bytes get immediately reserved in memory, 2 bytes each for the 8 integers (under Windows/Linux the array would occupy 32 bytes as each integer would occupy 4 bytes). And since the array is not being initialized, all eight values present in it would be garbage values. This so happens because the storage class of this array is assumed to be auto. If the storage class is declared to be static then all the array elements would have a default initial value as zero. Whatever be the initial values, all the array elements would always be present in contiguous memory locations. This arrangement of array elements in memory is shown in Figure
11.2.6 Bounds Checking
In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; probably on top of other data, or on the program itself. This will lead to unpredictable results, to say the least, and there will be no error message to warn you that you are going beyond the array size. In some cases the computer may just hang. Thus, the following program may turn out to be suicidal.
void main( )
{
int num[40], i ;
for ( i = 0 ; i <= 100 ; i++ )
num[i] = i ;
}
Thus, to see to it that we do not reach beyond the array size is entirely the programmer’s botheration and not the compiler’s.
11.3 Two Dimensional Arrays
So far we have explored arrays with only one dimension. It is also possible for arrays to have two or more dimensions. The two-dimensional array is also called a matrix.
Here is a sample program that stores roll number and marks obtained by a student side by side in a matrix.
void main( )
{
int stud[4][2] ; int i, j ;
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n Enter roll no. and marks" ) ;
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
}
for ( i = 0 ; i <= 3 ; i++ )
{
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ;
}
}
There are two parts to the program—in the first part through a for loop we read in the values of roll no. and marks, whereas, in second part through another for loop we print out these values.
Look at the scanf( ) statement used in the first for loop:
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ;
In stud[i][0] and stud[i][1] the first subscript of the variable stud, is row number which changes for every student. The second subscript tells which of the two columns are we talking about—the zeroth column which contains the roll no. or the first column which contains the marks. Remember the counting of rows and columns begin with zero. The complete array arrangement is shown below.
11.3.1 Initializing a 2-Dimensional Array
How do we initialize a two-dimensional array? As simple as this...
int stud[4][2] = { { 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ;
or even this would work...
int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;
of course with a corresponding loss in readability.
It is important to remember that while initializing a 2-D array it is necessary to mention the second (column) dimension, whereas the first dimension (row) is optional.
Thus the declarations,
int arr[2][3] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][3] = { 12, 34, 23, 45, 56, 45 } ;
are perfectly acceptable,
whereas,
int arr[2][ ] = { 12, 34, 23, 45, 56, 45 } ;
int arr[ ][ ] = { 12, 34, 23, 45, 56, 45 } ;
would never work.
11.3.2 Memory Map of a 2-Dimensional Array
Let us reiterate the arrangement of array elements in a two-dimensional array of students, which contains roll nos. in one column and the marks in the other.
The array arrangement shown in Figure 8.4 is only conceptually true. This is because memory doesn’t contain rows and columns. In memory whether it is a one-dimensional or a two-dimensional array the array elements are stored in one continuous chain. The arrangement of array elements of a two-dimensional array in memory is shown below:
We can easily refer to the marks obtained by the third student using the subscript notation as shown below:
printf ( "Marks of third student = %d", stud[2][1] ) ;
Can we not refer the same element using pointer notation, the way we did in one-dimensional arrays? Answer is yes. Only the procedure is slightly difficult to understand. So, read on...
http://www.c-lang.thiyagaraaj.com/tutorials/c-concepts/c-array