Professional Documents
Culture Documents
Chapter-10
Arrays
Introduction
l Arrays are also known as subscript variable.
l Array is a collection of similar elements
l Whatever may the size of array, it always consumed memory in a contiguous
manner
Need of array
Till now we have been designing solution to small problems that require less number of
variables to handle program data. Think about a scenario where you need to handle
hundreds of variables or even more than that.
In such scenario, you might be thinking about what variable names should be used, how
to reduce redundant code, etc.
Assume you have to store marks of 100 students and then think about the following:
1) What could be your variable naming convention?
2) How you efficiently write input instruction to store 100 data.
3) How could you easily manipulate data like adding all of them in a less complex
style?
The answer to all these questions is subscript notation also known as arrays.
Array Declaration
When you want to create large number of variables you need not to think about 100s of
names. Assume that you want to create 100 variables to store marks of 100 students.
Here is the way:
int marks[100];
1) Notice square brackets after array name marks. This pair of square brackets is
used to depict array usage.
2) Number mention in the square bracket is size of array. In our example we wrote
100, so size of the array is 100. Thus we have declared 100 variables in one go.
3) These 100 variables are all of type int. Since array is a collection of similar
elements, data type for all 100 variables is int.
4) Name of the first variable is marks[0], second variable is marks[1], and so on.
Therefore the last variable is marks[99]. Here it is important to note that in C
language array indexing starts with 0 and not from 1.
Example: Program to calculate average of 10 marks
#include<stdio.h>
#include<conio.h>
0th array
1st array
1) Total numbers of blocks are 6, they are all of type int. Memory allocation done is
always sequential but we can assume it as two arrays each of size 3.
2) Logically we can see it as a row column structure. First row is your 0th array and
second row is 1st array.
3) Two dimensional arrays are used to handle data which is logically two
dimensional like matrix.
Example: Program to add two matrix of order 3 x 3.
#include<conio.h>
#include<stdio.h>
main()
{
int a[3][3],b[3][3],c[3][3];
int i,j;
clrscr();
printf("Enter 9 numbers for first matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("Enter 9 numbers for second matrix\n");
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
for(i=0;i<3;i++)
for(j=0;j<3;j++)
c[i][j]=a[i][j]+b[i][j];
printf("\nSum of matrix is: \n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)