Arrays
Hello Reader. I am writing this article on Arrays as per my knowledge. Hope So you will get good knowledge.
Introduction
The primary variables which we have discussed so far, such as ordinary ints, floats and chars, are capable of holding one value only. For example:
int a;char c;
float b;
Here the variables a, b and c are capable of storing one value at a time, that is we can not store more than one value in a, b and c at a time. But in our daily life we have come across many such situations where we need to refer a group of similar data by a single name, say a set of 100 integer values or a set of 500 real values or a set of 50 characters. For example, let you want to store 100 integer variables, then there are two ways to do so:
- either use 100 different integer variables, say n1, n2, n3,….,n100
- or use a common name to all 100 integers and then refer to each integer in terms of its position within the list of items
The former approach naturally does not seem so good. But the later approach is beneficial for the C compiler as well as for the programmer. The later approach is done using an entity called an array. An array is basically a group of data items, which are similar in nature and that, are differentiated from one another by their position within the array. In the subsequent sections we will discuss various types of arrays.
One Dimensional Array
A one-dimensional array is a structured collection of similar data items whose individual item can be accessed by using an index that indicates the position within the collection.
A typical one-dimensional array is defined as:
data-type array-name [size];
Here data-type describes the type of data stored in each location of array and array-name is the name associated with the set of values. The name of the array can not be the same as that of any other variable declared within the function. Finally the size is a positive integer constant which instructs the C compiler how many space should be reserved. The size of the array is specified using the subscript notation ([ ]). The subscript used to declare an array is called a dimension.
For example, if we want to store 100 integer values then its array declaration will be as:
int ival[100];
Similarly, if we want to store 50 real numbers then its array declaration will be as:
float fval[50];
Here ival and fval are array names that can store 100 values of data type integers and 50 values of data type float.
Accessing Array Elements
An individual array element of an array is accessed by writing the name of the array variable, followed by an expression that results in a positive integer value, enclosed with in square bracket as:
array-name [expression]
The numbering of elements in an array starts from 0.
For example, if we have an integer array as:
int val[100];
then
1st data item in this declaration is referred as val[0]2nd data item in this declaration is referred asval[1]
3rd data item in this declaration is referred as val[2]
…. …. ….
…. …. ….
…. …. ….
98th data item in this declaration is referred as val[97]
99th data item in this declaration is referred as val[98]
100th data item in this declaration is referred as val[99]
Thus the ith data item is referred to as
val[i-1]
We can assign an individual element of an array, read a value into it, writes its contents, pass it as a parameter and use it in an expression.
Thus if we want to access say 40th location in array val[], then we will use following notation:
item = val[39] ;
and if we want to store an integer 28 at 60th location then we will assign it as:
val[59] = 28 ;
Reading data items into array
Generally we read data items into array from 0 to (size-1), where size contains the actual size of an array, using for loop as:
for (i = 0; i<= size-1; i++)
{
printf(“Please enter array element #%d := ”, i+1);
scanf(“%d”, &val[i]);
}
Here the first data item in array val [] is placed into location &val [0], that’s why i has 0 initial value and this process will be repeated until i reaches (size – 1). Like ordinary integer, we have placed the “address of” operator (&) on the left side of val [].
Displaying data items of array
On the same track if we want to display the data items of array val [], we will use the following for–loop:
for (i = 0; i <= size–1; i++)
printf(“\nArray element #%d : %d”, i+1, val[i]);
Now let us read a simple program that illustrates the concept of an array.
/* Program - 1.c */
#include
main()
{
int val[5];
int i;
for (i = 0; i<5; i++)
{
printf("Please enter array element #%d : ", i+1);
scanf("%d", &val[i]);
}
for (i = 0; i < 5; i++)
printf("\nArray element #%d : %d", i+1, val[i]);
}
When you run this program, you get following output….
Please enter array element #1 : 15
Please enter array element #2 : 20
Please enter array element #3 : 12
Please enter array element #4 : 41
Please enter array element #5 : 22
Array element #1 : 15
Array element #2 : 20
Array element #3 : 12
Array element #4 : 41
Array element #5 : 22
In this program, we have entered array elements through keyboard and displayed them on the screen.
Now let us see some examples of using one dimensional array.
Some Examples
Example-1 : Write a program that searches a data item from a set of 10 numbers using linear search.
/* Program - 2.c */
#include
main()
{
int val[10];
int i, item, flag;
flag = 0;
printf("\n");
for (i = 0; i<10; i++)
{
printf("Please enter array element #%d : ", i+1);
scanf("%d", &val[i]);
}
printf("\nEnter the data item to be searched : ");
scanf("%d", &item);
for (i = 0; i < 10; i++)
{
if (item == val[i])
{
flag = 1;
break;
}
}
if (flag == 1)
printf("\nItem %d found.", item);
else
printf("\nItem %d not found.", item);
}
Example-2 Write a program that sorts a set of numbers in ascending order using Selection sort.
/* Program - 3.c */
#include
main()
{
int num[10];
int i, j, temp, n;
n = 10; /* initialize n to the size of the array */
for (i = 0; i
{
printf("Please enter array element #%d : ", i+1);
scanf("%d", &num[i]);
}
printf("\nUnsorted list of elements is as....\n");
for (i = 0; i
printf("%d\t", num[i]);
for(i=0; i
{
for(j=i+1; j
{
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("\nSorted list of elements is as....\n");
for (i = 0; i
printf("%d\t", num[i]);
}
The output of this program is as….
Please enter array element #1 : 13
Please enter array element #2 : 9
Please enter array element #3 : 18
Please enter array element #4 : 23
Please enter array element #5 : 11
Please enter array element #6 : 55
Please enter array element #7 : 22
Please enter array element #8 : 32
Please enter array element #9 : 20
Please enter array element #10 : 15
Unsorted list of elements is as....
13 9 18 23 11 55 22 32 20 15
Sorted list of elements is as....
9 11 13 15 18 20 22 23 32 55
The output of this program is as….
Please enter array element #1 : 23
Please enter array element #2 : 44
Please enter array element #3 : 12
Please enter array element #4 : 61
Please enter array element #5 : 18
Please enter array element #6 : 42
Please enter array element #7 : 11
Please enter array element #8 : 22
Please enter array element #9 : 20
Please enter array element #10 : 46
Enter the data item to be searched : 11
Item 11 found.
Initialization of Single Dimensional Array
In earlier programs, we have read data items into array through keyboard. But like ordinary variables, you can also initialize the array elements at the time of declaration as follows:
int num[5] = {12, 15, -23, 45, 10};
float sal[6] = {10.54, 26.9, 345.98, -25.5, 45.25, -55.75};
Here array name num contains 5 integers and array sal contains 6 real values. The earlier declaration causes num[0] to be initialized to 12, num[1] to 15, and so on. Similarly sal[0] is initialized 10.54, sal[1] to 26.9, and so on. A semicolon will always follow the closing brace One main point to remember is that whenever we initialize array elements during its declaration it is not necessary to mention its size that is its size is optional. Thus the following statements are also valid statements:
int num[ ] = {12, 15, -23, 45, 10};
float sal[ ] = {10.54, 26.9, 345.98, -25.5, 45.25, -55.75};
What about the boundary Limitation of an Array
Since C does not provide any facility of checking the validity of the subscript while using arrays, therefore we access the data items of an array, it is totally our duty to remember the size of the array. The compiler will not flash any error message if you try to violate the boundary of an array in your program.
Please do not try to execute the following program on your system, otherwise be ready for some disastrous result because a wrong subscripting may overlap your some important data.
/* Program - 4.c */
#include
main()
{
int num[ ] = {12, 15, -23, 45, 10};
int i;
num[6] = 50;
num[7] = 52;
for (i = 0; i < 7; i++)
printf("\nArray element #%d : %d", i+1, val[i]);
}
Multidimensional Arrays
The concept of single dimensional array is extended to multidimensional array. In multidimensional arrays, we will discuss two-dimensional and three-dimensional arrays only. Firstly we will study two-dimensional array.
Two-dimensional Arrays
Two-dimensional array is basically a collection of similar components, structured in two dimensions. In other words, a two-dimensional array is that one which have more than one row and more than one column. Two-dimensional array is useful for representing games like chess, tic – tac – toe or Scrabble. So two-dimensional array is used to represent a table with rows and columns. Each data item (component) in a table is accessed by a pair of row and column numbers of the item in that table.
Figure 1 shows a two dimensional array that has 10 rows and 20 columns. Since the numbering starts from 0, therefore rows are accessed by an integer ranges from 0 to 9 and columns from 0 to 19. Each data item is accessed by a row-column pair, with the row a number in the range 0..9 and the column a number in the range 0..19.
Figure 1
A two dimensional array is defined in exactly the same way as a one dimensional array, except that two index types must be used rather than one. The syntax of defining a two-dimensional array is as:
data-type array-name [m][n] ;
Here array-name is the name of a two dimensional array, containing data items of data-type, of having ‘m’ number of rows and ‘n’ number of columns.
If we want to use a table of 5 rows and 6 columns of having integer values then we will define it as:
int num[5][6] ;
Here num is the name of two-dimensional array with dimensions (5*6).
Accessing data items of two dimensional arrays
An individual data item of a two dimensional array is accessed by specifying the row and column of a a two dimensional array as:
num [i][j]
where ‘i’ refers to the row number and ‘j’ refers to the column number.
Now the data item in 3rd row and 5th column is referred as:
num [2][4]
Reading data items into a Two-dimensional Array
We read in the values of two-dimensional array by using two nested for loop as:
for(i=0; i
{
for(j=0; j
scanf(“%d”, &num[i][j]);
}
Here the first data item in array num[] is placed into location &num[0][0], that’s why i and j have initial value 0 each and this process will be repeated until i reaches row and j reaches col. Like single dimensional array, it is necessary to place the “address of” operator (&) on the left side of num[].
Displaying data items of array
On the same track if we want to display the data items of array num[], we will use the following nested for–loop:
for(i=0; i
{
printf(“\n”);
for(j=0; j
printf(“%d”, num[i][j]);
}
Let us see a simple program that reads and displays the elements of a two-dimensional matrix.
/* Program - 5.c */
#include
main()
{
int num[3][4];
int i, j;
printf("\nReading the contents of a two dimensional matrix (3*4).\n");
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
{
scanf("%d", &num[i][j]);
}
}
printf("\nDisplaying the contents of a two dimensional matrix (3*4).\n");
for(i=0; i<3; i++)
{
printf("\n");
for(j=0; j<4; j++)
{
printf("%d\t", num[i][j]);
}
}
}
The output of this program is as….
Reading the contents of a two dimensional matrix (3*4).
13 20 8 1
25 10 32 27
19 21 44 16
Displaying the contents of a two dimensional matrix (3*4).
13 20 8 1
25 10 32 27
19 21 44 16
Initialization of a Two-Dimensional Array
Like single dimensional array, we can also initialize two-dimensional array during its declaration as:
int num[3][4] = {
{12, 15, 30, 42},
{32, 20, 83, 35},
{15, 67, 20, 13}
};
We can also initialize it as:
int num[3][2] = {11, 31, 53, 24, 15, 16};
While initializing a two dimensional array, the declaration of first dimension, that is row, is optional but the second dimension (column) declaration is not optional. The user has to explicitly mention the size of column. Thus the following statement is completely valid:
int num[][2] = {11, 12, 13, 14, 15, 16};
But the following statements will be completely invalid:
int num[][] = {11, 12, 13, 14, 15, 16};
int num[3][] = {11, 12, 13, 14, 15, 16};
Matrices
Since a two dimensional array has two dimensions, therefore matrices are excellent example of two-dimensional array. Now we will how to use two-dimensional arrays while solving matrices problems.
Some Examples
Let us study some examples based on matrices.
Example-1 : Write a program that adds two matrices.
/* Program - 6.c */
#include
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, row1, row2, col1, col2;
printf("\nEnter the row and column of first matrix : ");
scanf("%d %d", &row1, &col1);
printf("\nEnter the row and column of second matrix : ");
scanf("%d %d", &row2, &col2);
if ((row1 == row2) && (col1 == col2))
{
printf("\nReading the contents of first matrix (%d*%d).\n", row1, col1);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &a[i][j]);
}
}
printf("\nReading the contents of second matrix (%d*%d).\n", row2, col2);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &b[i][j]);
}
}
for(i=0; i
{
for(j=0; j
c[i][j] = a[i][j] + b[i][j];
}
printf("\nAddition of two matrices is as:\n");
for(i=0; i
{
printf("\n");
for(j=0; j
{
printf("%d\t", c[i][j]);
}
}
}
else
printf("\nYou have entered wrong dimensions.\n");
}
Here are some sample outputs of this program:
First Run:
Enter the row and column of first matrix : 3 4
Enter the row and column of second matrix : 4 4
You have entered wrong dimensions.
Second Run:
Enter the row and column of first matrix : 3 4
Enter the row and column of second matrix : 3 4
Reading the contents of first matrix (3*4).
1 2 3 4
5 6 7 8
9 1 2 3
Reading the contents of second matrix (3*4).
9 8 7 6
5 4 3 2
1 9 8 7
Addition of two matrices is as:
10 10 10 10
10 10 10 10
10 10 10 10
In this program, we are using three two dimensional arrays a, b and c. The size of all arrays are initially set to (10*10). In this program we firstly ask the user to provide the row and column of both matrixes before reading the data items into arrays. The number of rows and columns of both matrices should be same; otherwise we will get an error message. And remember that user has to keep in mind about the boundaries of array because the C compiler will not bother about this disaster. If above two conditions are fully satisfied then the elements of both ‘a’ and ‘b’ two-dimensional arrays are read.
Example-2 : Write a program that multiplies two matrices.
/* Program - 7.c */
#include
main()
{
int a[10][10], b[10][10], c[10][10];
int i, j, k, row1, row2, col1, col2;
printf("\nEnter the row and column of first matrix : ");
scanf("%d %d", &row1, &col1);
printf("\nEnter the row and column of second matrix : ");
scanf("%d %d", &row2, &col2);
if (col1 == row2)
{
printf("\nReading the contents of first matrix (%d*%d).\n", row1, col1);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &a[i][j]);
}
}
printf("\nReading the contents of second matrix (%d*%d).\n", row2, col2);
for(i=0; i
{
for(j=0; j
{
scanf("%d", &b[i][j]);
}
}
for(i=0; i
{
for(j=0; j
{
c[i][j] = 0;
for(k=0; k
c[i][j] += a[i][k] * b[k][j];
}
}
printf("\nMultiplication of two matrices is as:\n");
for(i=0; i
{
printf("\n");
for(j=0; j
{
printf("%d\t", c[i][j]);
}
}
}
else
printf("\nYou have entered wrong dimensions.\n");
}
Here are some sample outputs of this program:
First Run:
Enter the row and column of first matrix : 2 4
Enter the row and column of second matrix : 4 3
Reading the contents of first matrix (2*4).
2 4 5 6
1 6 3 8
Reading the contents of second matrix (4*3).
5 3 8
9 0 1
3 5 7
4 6 1
Multiplication of two matrices is as:
85 67 61
100 66 43
Second Run:
Enter the row and column of first matrix : 2 4
Enter the row and column of second matrix : 3 4
You have entered wrong dimensions.
Three Dimensional Arrays
C does not put any limit on the number of dimensions that an array can have. We understand three dimensional array concepts by following example. Let we want to keep the information of items, month wise, sold from different stores. Each data items that has been sold is represented by three indexes:
m-num – the month in which it was sold
s-num – the store numbers from where it was sold
i-num – which item number was sold
And its declaration is as:
int sales[m-num][s-num][i-num];
We know that two loops are necessary to access each component in a two-dimensional array, likewise it takes three loops to access each component in a three dimensional array. The only problem is to find out – which index controls the outer loop, the middle loop and the inner loop. If we want to calculate the monthly sales by the stores then month will control the outer loop and store will control the middle loop. If we want to calculate monthly sales by item number then month will control the outer loop and item number will control the middle.
For example, let you declare the three dimensional as:
int sales[12[5][10];
A graphical representation of the array variable sales is shown in figure-11.2. The number of data items in sales is 600 (12*5*10).
Figure 2
In following loop, we read in the values of array sales:
for (i=0; i
{
for (j=0; j
{
for (k=0; k < i-num; k++)
scanf(“%d”, &sales[i][j][k]);
}
}
Similarly if we want to print the output of sales report according to the item number sold from different stores monthwise, we will use following loops:
for (i=0 ; i < i-num ; i++)
{
for (j=0; j
{
for (k=0; k
printf(“%d”, &sales[i][j][k]) ;
printf(“\n”);
}
printf(“\n”);
}
Initialization of Three Dimensional Array
Like single dimensional array or two-dimensional array we can also initialize three-dimensional array as:
int sales [3][4][2] = {
{
{5, 3},
{6, 9},
{2, 7},
{9, 2}
},
{
{4, 3},
{1, 0},
{8, 2},
{1, 5}
},
{
{1, 12},
{56, 9},
{12, 27},
{99, 20}
},
{
{44, 33},
{21, 10},
{18, 82},
{11, 35}
}
};
Array of Characters
Since we know that an array is a collection of data items of the same data type that referenced by a single name. Earlier we have discussed about an array of ints or array of floats only. In this chapter we will also discuss an array of chars and their cousin string.
Like array of ints, we can have an array of characters. An array of chars is declared as:
char array-name [size];
Here array-name is the name of array containing data items of character type and the size is the total number characters in array-name.
For example, if we declare the following statement:
char ch[20] ;
Here ch is the name of an array, which is capable of storing 20 characters. The individual character of this array can be accessed by using a subscript or an index as:
ch[index_no];
Like an array of int, the array indexes starts from 0 in array of chars also. It means that if we want to refer the 5th element of ch[] array then we write as:
ch [4]
Similarly you can access other data items of this character array.
The way you read the data items of integer array, you read the data items of character array as:
for (i=0; i
scanf(“%c”, &ch[i]);
And the procedure of writing the output of character array is also same, as follows:
for (i=0; i
printf(“%c”,ch[i]);
Following program illustrates the concept of an array of char:
/* Program - 9.c */
#include
main()
{
char ch[11];
int i;
printf("\nPlease enter any 11 characters : ");
for(i=0; i<11; i++)
scanf("%c", &ch[i]);
printf("\nYou have entered these characters : ");
for(i=0; i<11; i++)
printf("%c",ch[i]);
}
The output of this program is as….
Please enter any 11 characters : Atishrestha
You have entered these characters : Atishrestha
And like array of int, the characters of ch-array are also stored in consecutive memory locations as shown below:
64000
64002
64004
64006
64008
64010
64012
64014
64016
64018
64020
A t i s h r e s t h a
Since, in C each character occupies one byte in memory that’s why the difference between two adjacent characters is 1.
Initialization of Character array
Like array of ints or floats, we can also initialize an array of char during its declaration as:
char ch[11] = {‘A’, ‘t’, ‘i’, ‘s’, ‘h’, ‘r’ , ‘e’, ‘s’, ‘t’, ‘h’, ‘a’};
or we can also write it as:
char ch[] = {‘A’, ‘t’, ‘i’, ‘s’, ‘h’, ‘r’ , ‘e’, ‘s’, ‘t’, ‘h’, ‘a’};
It means that if we initialize the character array during its declaration, then the size declaration is optional, and it is the duty of user to remember the number of characters stored in the array.