Arrays
Introduction
• We have used fundamental data types namely char, int, float which
are very useful.
• But the variable of these types stores only one value at a given
time.
• In various applications, we need to handle large amount of data in
terms of reading, processing and printing.
• To process such data we require a data type that would facilitate
efficient storing, accessing and manipulation of data items.
• C supports a derived data type known as array.
• An array is a fixed-size sequenced collection of elements of the
same data type.
• An array can also be defined as follows...
• An array is a collection of similar data items stored in continuous
memory locations with single name.
• Examples:
– List of numbers: Test scores of a class of students.
– List of names: list of employees in a company.
• Array provides a convenient structure for representing data, so it is
classified as data structures in C.
• For example, we can use array name salary to represent a set of salaries of
a group of employees in an organization.
• To refer to the individual salaries by writing a number called index or
subscript in brackets after the array name.
elements salary
18000 25000 30000 32000 ... ...
0 1 2 3 ... ...
• salary[2] represents the salary of 3rd employee
• This enables us to develop concise and efficient programs.
Types of arrays
• Arrays not only represent lists of values but also tables of data in 2,
3 or more dimensions.
• Types of arrays:
– One dimensional arrays
– Two dimensional arrays
– Three dimensional arrays
One dimensional array
• It is a list of items can be given one variable name using only one
subscript.
• Ex: array of five numbers (15,8,84,14,29) represented with a variable
name number:
int number[5];
Array elements
Five storage locations are assigned
number[0] = 15;
number[0]
number[1] = 8;
number[1]
number[2] number[2] = 84;
number[3] number[3] =14;
number[4] number[4] =29;
Declaration of 1-D array
• Array declaration
type variable_name[ size ];
Type of elements
that will be in array Maximum number of elements
stored inside the array
float height[50];
int group[4*5];
• The size should be a numeric constant or constant expression.
• C language treats character strings as arrays of characters.
• The size in the string represents the maximum number of
characters that the string can hold. ‘w’ name[0]
char name[10]=“well done”; ‘e’ name[1]
‘l’ name[2]
• If name holds the string ‘well done’ then each character of
‘l’ name[3]
string is treated as element.
‘‘ name[4]
• Character string terminate with null character ‘\0’. Thus ‘d’ name[5]
name[9] holds null character. ‘o’ name[6]
‘n’ name[7]
• So extra space for null character should be allowed.
‘e’ name[8]
‘\0’ name[9]
Memory allocation of an array
#include<conio.h>
void main()
{
int a[]={25,23,21,42};
int i;
clrscr();
for(i=0;i<4;i++)
{
printf("a[%d]=%d\n",i,a[i]);
printf("adress=%u\n",&a[i]);
}
getch();
}
Initialization
• After array is declared its variables are to initialized.
• An array can be initialized at either of the following stages:
– At compile time
– At run time
Compile time initialization
type array_name[size] = {list of values};
int number[3] = {54,99,12};
• Remaining elements initialized to zero or NULL.
int num[10] = {1,5,8};
float total[5] = {0.5,15.8,-10};
char[8] = {‘n’, ‘i’, ‘k’};
• Enough space for initialized variable
int counter[] = {1,1,1};
char name[] = {‘M’, ‘i’, ‘c’, ‘k’, ‘y’, ‘\0’};
char name[] = “Micky”;
• Compile time initialization may be partial. That is number of elements may
be less than declared size.
• In such cases remaining elements are initialized to zero, if the array type is
number and NULL if the type is char.
int number [2] = {10,20,30};
• If the initializers are more than the declared size, the compiler will
produce error.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,number[10]={1,5,8};
float num[5]={0.5,15.8,-10};
char name[8]={'n','i','k'};
clrscr();
for(i=0;i<10;i++)
{
printf("number[%d] = %d\n",i,number[i]);
}
for(i=0;i<5;i++)
{
printf("num[%d] = %f\n",i,num[i]);
}
for(i=0;i<8;i++)
{
printf("name[%d] = %c\n",i,name[i]);
}
getch();
}
Run time initialization
• scanf is used to initialize an array.
int marks[2];
scanf(“%d %d %d”, &marks[0], &marks[1]);
• It initializes the array elements with values entered through the
keyboard.
Read and display array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[5], i;
printf(“enter array elements:”);
for(i = 0; i < 5; i++)
{
scanf("%d", &arr[i]);
}
printf("\nPrinting elements of the array: \n\n");
for(i = 0; i < 5; i++)
{
printf("%d ", arr[i]);
}
getch();
}
Program to find average marks obtained by 10 students in a test
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0, avg, i, marks[10];
clrscr();
for(i=0;i<10;i++)
{
printf("Enter marks:");
scanf("%d",&marks[i]); or scanf("%d",(marks+i));
}
for(i=0;i<10;i++)
{
sum=sum+ marks[i]); or sum=sum+ *(marks+i);
}
avg=sum/10;
printf("\nAverage marks= %d\n", avg); or printf("\nAverage marks= %d\n", sum/10);
getch();
}
Notations for retrieving array elements
#include<stdio.h>
#include<conio.h>
void main()
{
int a[]={25,23,21,42};
int i;
clrscr();
for(i=0;i<4;i++)
{
printf("address=%u, ",&a[i]);
printf("a[%d]=%d %d %d %d \n",i,a[i], *(a+i), *(i+a), i[a]);
}
getch();
}
Program to find largest and smallest number of the array.
#include<stdio.h> printf("The largest element is %d",large);
#include<conio.h> printf("\nThe smallest element is
void main() %d",small);
{ getch();
int a[50],i,n,large,small; }
printf("How many elements:");
scanf("%d",&n); Output:
printf("Enter the Array:");
for(i=0;i<n;++i)
{
scanf("%d",&a[i]);
}
large=small=a[0];
for(i=1;i<n;++i)
{
if(a[i]>large)
large=a[i];
if(a[i]<small)
small=a[i];
}
2-Dimensional array
• Two dimensional array is called a matrix.
• Declaration: columns
type array_name [rows][cols];
rows
Ex: int student_marks[4][2];
– int specifies type of element in each slot
– student_marks specifies name of the array
– [4] specifies number of rows
– [2] specifies number of columns
Initialization of 2-D array
• Initialization at the time of declaration.
int stud[4][2] = { {101,56}, {102,80},{103,33},{104,78}};
int stud[4][2] = { 101,56, 102,80,103,33,104,78};
Number of rows Number of columns
• Column dimension is necessary and row dimension is optional.
• In the declaration of two dimensional array the column size should be
specified, to that it can arrange the elements in the form of rows and
columns.
• int stud[4][2] = { {101,56}, {102,80},{103,33},{104,78}};
Col 0 Col 1
Row 0 101 56
Row 1 102 80
Row 2 103 33
Row 3 104 78
• 2-d array is collection of a number of 1-d arrays placed one below
the other conceptually.
• A 1-d or a 2-d array elements are stored in one continuous chain.
stud[0][0] stud[0][1] stud[1][0] stud[1][1] stud[2][0] stud[2][1] stud[3][0] stud[3][1]
101 56 102 80 103 33 104 78
65508 65510 65512 65514 65516 65518 65520 65522
Basic program to initialize array, print the array
elements and its respective address
#include<conio.h>
void main()
{
int students[4][2]={101,88,102,97,103,65,104,85};
int i,j;
clrscr();
for(i=0;i<4;i++)
for(j=0;j<2;j++)
{
printf("students[%d][%d] = %d”, i,j,students[i][j]);
printf(“ address = %u\n", &students[i][j]);
}
getch();
}
Read and display 2-D array
#include<stdio.h> for(i=0; i<row; i++)
#include<conio.h> {
void main() for(j=0; j<col; j++)
{ {
int arr[10][10], row, col, i, j; printf("%d ",arr[i][j]);
clrscr(); }
printf("Enter number of row for Array (max 10) : printf("\n");
"); }
scanf("%d",&row); getch();
printf("Enter number of column for Array (max }
10) : ");
scanf("%d",&col);
printf("Now Enter %d*%d Array Elements :
",row, col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
scanf("%d",&arr[i][j]);
}
}
printf("The Array is :\n");
Output
• Each row of 2-d array can be though of as a 1-d array. (important
fact)
• Ex: int s[4][2];
• Four 1-d arrays with 2 elements each
• We refer 1-d array using a single subscript
• If we imagine s as 1-d array then we can refer elements as s[0],
s[1],.. So on.
• s[0] gives address of zeroth 1-d array, s[1] gives address of first 1-d
array and so on.
s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]
101 56 102 80 103 33 104 78
65508 65510 65512 65514 65516 65518 65520 65522
• Now we are able to reach each 1-d array.
Program to show how 2-D array is stored
#include<conio.h>
void main()
{
int s[4][2]={101,88,102,76,103,54,104,46};
clrscr();
printf("Base Address = %u\n",s);
printf("zeroth 1-d address = %u\n",s[0]);
printf("first 1-d address = %u\n",s[1]);
printf("second 1-d address = %u\n",s[2]);
printf("third 1-d address = %u\n",s[3]);
getch();
}
s[0][0] s[0][1] s[1][0] s[1][1] s[2][0] s[2][1] s[3][0] s[3][1]
101 88 102 76 103 54 104 46
65510 65510 65512 65514 65516 65518 65520 65522
Addition of two matrices
#include<conio.h> printf("\nMatrix 2:\n");
void main() for(i=0; i<3; i++)
{ {
int mat1[3][3], mat2[3][3], mat3[3][3], i, j, k; for(j=0; j<3; j++)
clrscr(); {
printf("Enter first matrix element (3*3) : "); printf("%2d ",mat2[i][j]);
for(i=0; i<3; i++) }
for(j=0; j<3; j++) printf("\n");
scanf("%d",&mat1[i][j]); }
printf("Enter second matrix element (3*3) : "); //Addition of 2 matrices
for(i=0; i<3; i++) printf("\nsum matrix:\n");
for(j=0; j<3; j++) for(i=0; i<3; i++)
scanf("%d",&mat2[i][j]); for(j=0; j<3; j++)
printf("\nMatrix 1:\n"); mat3[i][j]=mat1[i][j]+mat2[i]
for(i=0; i<3; i++) [j];
{ //print sum matrix
for(j=0; j<3; j++) for(i=0; i<3; i++)
{ {
printf("%2d ",*(*(mat1+i) for(j=0; j<3; j++)
+j)); {
} printf("%2d ",mat3[i][j]);
printf("\n"); }
} printf("\n");
}
getch();
}
Output
Multiplication of 2 matrices
#include<conio.h> printf("Enter second matrix (%d*%d) : ",p,q);
void main() for(i=0; i<p; i++)
{ for(j=0; j<q; j++)
int mat1[5][5], mat2[5][5], mat3[5][5], i, j, k, m, scanf("%d",&mat2[i]
n, p, q; [j]);
clrscr(); printf("\nMatrix 1:\n");
printf("Enter first matrix dimensions: "); for(i=0; i<m; i++)
scanf("%d %d",&m, &n); {
printf("Enter second matrix dimensions: "); for(j=0; j<n; j++)
scanf("%d %d", &p, &q); printf("%2d ",mat1[i]
if(n!=p) [j]);
{ printf("\n");
printf("Enter valid dimensions\n"); }
exit(); printf("\nMatrix 2:\n");
} for(i=0; i<p; i++)
printf("Enter first matrix (%d*%d) : ",m,n); {
for(i=0; i<m; i++) for(j=0; j<q; j++)
for(j=0; j<n; j++) printf("%2d ",mat2[i]
scanf("%d",&mat1[i] [j]);
[j]); printf("\n");
}
//Multiplication of 2 matrices
printf("\nMultiplication matrix:\n");
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
mat3[i][j]=0;
for(k=0; k<n; k++)
mat3[i][j] = mat3[i][j]+mat1[i][k] *mat2[k][j];
}
}
//print Multiplied matrix
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
printf("%2d ",mat3[i][j]);
}
printf("\n");
}
getch();
}
Transpose of a matrix
#include<conio.h> for(i=0; i<3; i++)
void main() {
{ for(j=0; j<3; j++)
int mat1[3][3], mat2[3][3], i, j; {
clrscr(); mat2[i][j]=mat1[j][i];
printf("Enter first matrix element (3*3) : "); }
for(i=0; i<3; i++) }
{ //print transpose matrix
for(j=0; j<3; j++) printf(“\nTranspose Matrix:\n”);
{ for(i=0; i<3; i++)
scanf("%d",&mat1[i][j]); {
} for(j=0; j<3; j++)
} {
printf("\nMatrix 1:\n"); printf("%2d ",mat2[i][j]);
for(i=0; i<3; i++) }
{ printf("\n");
for(j=0; j<3; j++) }
{ getch();
printf("%2d ",mat1[i][j]); }
}
printf("\n");
}
//Transpose of matrix 1
Output
#include<conio.h> for(i=0; i<2; i++)
void main() {
{ for(j=0; j<3; j++)
int mat1[3][2], mat2[2][3], i, j; {
clrscr(); mat2[i][j]=mat1[j][i];
printf("Enter first matrix element (3*2) : "); }
for(i=0; i<3; i++) }
{ //print transpose matrix
for(j=0; j<2; j++) printf("\nTranspose Matrix:\n");
{ for(i=0; i<2; i++)
scanf("%d",&mat1[i][j]); {
} for(j=0; j<3; j++)
} {
printf("\nMatrix 1:\n"); printf("%2d ",mat2[i][j]);
for(i=0; i<3; i++) }
{ printf("\n");
for(j=0; j<2; j++) }
{ getch();
printf("%2d ",mat1[i][j]); }
}
printf("\n");
}
//Transpose of matrix 1
Output
Program to find trace of a matrix
#include<conio.h> printf("%2d ",mat1[i][j]);
void main() }
{ printf("\n");
int mat1[3][3], i, j, sum; }
clrscr(); //Trace of matrix 1
sum=0; for(i=0; i<3; i++)
printf("Enter first matrix element (3*3) : "); {
for(i=0; i<3; i++) sum=sum+mat1[i][i];
{ }
for(j=0; j<3; j++) //print trace matrix
{ printf(“\nTrace of Matrix1 = %d\n”, sum);
scanf("%d",&mat1[i][j]); getch();
} }
}
printf("\nMatrix 1:\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
Output
Program to find normal of a matrix
#include <stdio.h> }
#include <math.h> printf("\nMatrix :\n");
void main () for(i=0; i<m; i++)
{ {
int array[10][10]; for(j=0; j<n; j++)
int i, j, m, n, sum , normal; {
clrscr(); printf("%2d ",array[i][j]);
sum=0; sum=sum+ array[i][j] * array[i][j];
printf("Enter the order of the matrix\n"); }
scanf("%d %d", &m, &n); printf("\n");
printf("Enter the elements of the matrix \ }
n"); normal = sqrt(sum);
for (i = 0; i < m; ++i) printf("The normal of the matrix is =
{ %d\n", normal);
for (j = 0; j < n; ++j) getch();
{
scanf("%d", &array[i][j]); }
}
Output
Applications of arrays
• Arrays are used to Store List of values
– In c programming language, single dimensional arrays are used
to store list of values of same datatype. In other words, single
dimensional arrays are used to store a row of values. In single
dimensional array data is stored in linear form.
• Arrays are used to Perform Matrix Operations
– We use two dimensional arrays to create matrix. We can
perform various operations on matrices using two dimensional
arrays.
• Arrays are used to implement Search Algorithms
– We use single dimensional arrays to implement search
algorihtms like ...
• Linear Search
• Binary Search
• Arrays are used to implement Sorting Algorithms
– We use single dimensional arrays to implement sorting
algorihtms like ...
• Insertion Sort
• Bubble Sort
• Selection Sort
• Quick Sort
• Merge Sort, etc.,
• Arrays are used to implement Data structures
– We use single dimensional arrays to implement datastructures
like...
• Stack Using Arrays
• Queue Using Arrays
• Arrays are also used to implement CPU Scheduling Algorithms