Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Arrays Syllabus:: Arrays: Concepts, Definition, Declaration, Accessing Elements, Storing

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

ARRAYS

Syllabus:
Arrays: concepts, definition, declaration, accessing elements, storing
elements, arrays and functions, two-dimensional and multi-dimensional
arrays, applications of arrays.

Contents
S.No Topic Page No.
1 Concept of Array
2 Definition of array
3 Declaration of Arrays
3.1 Example program
4 Accessing Elements
4.1 Calculating the addressing of array elements
4.1.1 Example
5 Storing Elements
5.1 Initialization of arrays
5.2 Input values to the elements of array
5.3 Assign Values to the elements
5.4 Calculating the length of the array
5.5 operations on arrays
6 Arrays and Functions
6.1 Passing individual elements
6.1.1 Passing Data Values
6.1.2 Passing Addresses
6.2 Passing entire Array
7 Sample Programs
8 Review Questions
8.1 Long answer Questions
8.2 Short Answer Questions
9 Snippet Programs
10 List of Figures
11 List of Tables
1.CONCEPTS

 The fundamental data types, namely char, int, float, double are
used to store only one value at any given time.
 Hence these fundamental data types can handle limited amounts of
data.
 In some cases we need to handle large volume of data in terms of
reading, processing and printing.
 To process such large amounts of data, we need a powerful data type
that would facilitate efficient storing, accessing and manipulation of
data items.
 “C‟ supports a derived data type known as array that can be used for
such applications.

Derived Types
2.Arrays: (Definition)
 An array is a fixed size sequenced collection of elements of the same
data type.

Or
 An array is collection of same data type elements in a single entity.

Or
 An array is collection of homogeneous elements in a single variable.

 It allocates sequential memory locations.

 Individual values are called as elements.


Some examples where arrays can be used are
1) List of temperatures recorded every hour in a day, or a month, or a year.
2) List of employees in a company.
3) List of products and their cost sold by a store.
4) List of students in a class.
5) List of customers and their telephone numbers.

3.DECLARATION OF ARRAYS

Like any other variables, arrays must be declared before they are used.

Arrays are declared using the following syntax:

Syntax: <datatype> <array_name>[size of array];

 Data Type: What kind of values array can store (Example: int, float,
char).
 array_name:To identify the array.
 Size of array(INDEX): The maximum number of values that the array
can hold.
Example:
int marks[10];
 The above statement declares a marks variable to be an array
containing 10 elements.
 In C, the array INDEX (also known as subscripts) starts from zero.
This means that the array marks will contain 10 elements in all.
 The first element will be stored in marks[0]
 The second element will be stored in marks[1]
 .
 .
 .
 The tenth element will be stored in marks[9].
Ist 2nd 3rd 4th 5th 6th 7th 8th 9th 10th
eleme eleme eleme eleme eleme eleme eleme
eleme elem eleme
nt nt nt nt nt nt nt
nt ent nt
marks mark mark mark mark mark mark mark mark mark
[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]

Memory representation of an array of ten elements

3.1 Example-1: Write a program to print bytes reserved for various types of
data and space required for storing them in memory using array.
# include<stdio.h>
main ( )
{
int a[10];
char c[10];
float b[10];
printf(“the type “int” requires %d bytes”, sizeof(int));
pirntf(“ \n The type “char” requires %d bytes”, sizeof(char));
printf(“ \n The type “float” requires %d bytes”, sizeof(float));
printf(“ \n %d memory locations are reserved for ten “int” elements”,
sizeof(a));
printf (“ \n %d memory locations are reserved for ten “char”
elements”,sizeof(c));
printf (“ \n %d memory locations are reserved for ten “float”
elements”,sizeof(b));
}
Output:
The type “int” requires 2 bytes
The type “char” requires 1 bytes
The type “float” requires 4 bytes
20 memory locations are reserved for ten “int‟ elements
10 memory locations are reserved for ten “char‟ elements
40 memory locations are reserved for ten “float‟ elements.
4.ACCESSING ELEMENTS OF THE ARRAY
 For accessing an individual element of the array, the array INDEX
(Subscript) must be used
 For example to access the fourth element of the array, you must write
array[3].
 To access all the elements of the array, we must use a loop.
 That is we can access all the elements of the array by varying the
value of the index into the array.

Example:
// Set each element of the array to 10

int I marks[5];
for(i=0;i<5;i++)
marks[i]=10;

Explanation:
 The code accesses every individual element of the array and sets its
value to 10
 In the for loop, first the value of marks[0] is set to 0, then the index(i)
incremented and the next value i.e., marks[1] is set to 10.
 The procedure is continued until all the 5 elements of the array are
set to 10.

10 10 10 10 10
[0] [1] [2] [3] [4]
The array marks after executing the code
 The name of the array is a symbolic reference for the address to the
first byte of the array. Therefore, whenever we use the array name, we
are actually referring to the first byte of that array. The index specifies
an offset from the beginning of the element being referred.
Valid Statements:

 a = number[0] + 10;

 number[4] = number[0] + number[2];


 number[2] = x[5] + y[10];

 value[6] = number[i] * 3;

NOTE: The Index must be an integral value or an expression that


evaluates to an integral value.

4.1CALCULATING THE ADDRESS OF ARRAY ELEMENTS:


 C can calculate the address of any element in the array.
 An array stores all its data elements in consecutive memory locations.
 So, storing just the basic address, that is the address of the first
element in the array is sufficient.
 The address of other data elements can simply be calculated using the
Base Address (BA).
The formula is
Address of Data Element, A[k] = BA[A] + w ( k - lower_bound)

 Here A is the array.


 K is the index of the element for which we have to calculate the
address.
 BA is the base address of the array A
 W is the word size of one element in memory(example , size of float 4)
 Lower_Bound is the index of the first element in the array.
4.1.1EXAMPLE:

float avg[ ]={99.0,31.2,41.31,67.0,78.0,43.0}


Calculate address of avg[4] if base address=1000

99.0 31.2 41.31 67.0 78.0 43.0


[0] [1] [2] [3] [4] [5]
1000 1004 1008 1012 1016 1020

We know that storing a floating point number requires 4 bytes.


Therefore word size w=4
we know the formula is
A[k] = BA[A] + w ( k - lower_bound)

Here k=4, w=4, BA=1000, lower_bound=0


avg[4] = 1000 + 4 ( 4 – 0 )
= 1000 + 4(4)
= 1016

5.STORING ELEMENTS IN ARRAYS

 When we declare and define an array, we are just allocating space for
the elements; no values are stored in the array.
 To store values in the array, there are three(3) ways:
a) Initialize the elements
b) Input the values for the elements
c) Assign values to the elements
Initialize the
elements

e Store values
in the array Input values for
the elements

Assign values to
the elements

Storing values in an Array


5.1 Initialization of arrays:

 Elements of the array can be initialized at the time of declaration as in


the case of every other variable.
Syntax:
type array_name[size] = { list of values };
 The values are written with curly brackets and every value is separated
by a comma.
 It is a compiler error to specify more number of values than the number
of elements in the array.

Example:
int marks[5] = { 90, 31, 41, 9, 88}

 An array with name marks is declared that has space that is enough
to store 5 elements.
 The first element i.e., marks[0] is assigned with the value 90.
 Similarly the second element of the array i.e., marks[1] is assigned
with the value 31 and so on.
Marks[0] 90
Marks[1] 31
Marks[2] 41
Marks[3] 9
Marks[4] 88

Initialization of marks[5]

While initializing the array at the time of declaration , the programmer may
omit to mention the size of the array.
Example:
int marks[ ]={90,31,41};
 Here the compiler will allocate enough space for all initialized
elements.
 If the number of values provided is less than the number of elements
in the array, the un-assigned elements are filled with zeroes.

int marks [5]= { 90, 45, 67, 85, 78 }


90 45 67 85 78
[0] [1] [2] [3] [4]

int marks [5]= { 90, 45 }


90 45 0 0 0
[0] [1] [2] [3] [4]
int marks [ ]= { 90, 45, 67, 85, 78, 31 }
90 45 67 85 78 31
[0] [1] [2] [3] [4] [5]
int marks [5]= { 0 }
0 0 0 0 0
[0] [1] [2] [3] [4]

Initialization of array elements


5.2 INPUTTING VALUES:

An array can be filled by inputting values from the keyboard.


In this method, a while/do-while or a for loop is executed to input the
value for each element of the array.
EXAMPLE:
// Input value of each element of the array

int i,marks[5];
for (i=0;i<5;i++)
scanf(“%d”,&marks[i]);

Code for inputting each element of the array

Explanation:
In the code, we start with the index I at o and input the value for the first
element of the array.
Since the array have 5 elements, we must input values for elements whose
index varies from 0 to 4.
Therefore in the for loop, we test for condition (i<5) which means the
number of elements in the array.
5.3 Assigning Values:
 The third way to assign values to individual elements of the array is
by using the assignment operator.
 Any value that evaluates to an appropriate data type as that of the
array can be assigned to the individual array element.
 A simple assignment statement can be written as
marks[3] = 100;

 Here, 100 is assigned to the fourth element of the array.


 We cannot assign one array to another array, evn if the two arrays
have the same type and same size.
 To copy an array, you must copy the value of every element of the first
array into the elements of the second array.

// copy an array at the individual element level

int i,array1[5],array2[5];
for(i=0;i<5;i++)
array[1]=array[2];

Code to copy an array at the individual element level


EXPLANATION:
The code accesses each element of the first array and simultaneously
assigns its value to the corresponding element of the second array.
Finally, the index value I is incremented to access the next element in
succession.
Therefore, after the execution of code we have

array1[0]=array2[0], array1[1]=array2[1] and so on…


5.4 CALCULATING THE LENGTH OF THE ARRAY:
 Length of the array is given by the number of elements stored in it.
 The general formula to calculate the length of the array is
Length = upper_bound – lower_bpund + 1

 Where upper_bound is the index of the last element and lower_bound


is the index of the first element in the array.
EXAMPLE:
Let be an array of integers such that
age[0]=2 age[1]=5 age[2]=3 age[3]=1 age[4]=7
SOLUTION:

2 5 3 1 7
age[0] age[1] age[2] age[3] age[4]

FORMULA is: Length = upper_bound – lower_bpund + 1


Here lower_bound=0, upper_bound=4
Therefore, Length= 4 – 0 + 15

5.5 OPERATIONS THAT CAN BE PERFORMED ON ARRAYS:


There are a number of operations that can be performed on arrays. They are
 Traversal
 Insertion
 Search
 Deletion
 Merging
 sorting
6 ARRAYS AND FUNCTIONS
 Like variables of other data types, we can also pass an array to a
function.
 While in situations, you may want to pass individual elements of the
array and in other situations you may want to pass the entire array.

One-Dimensional
Arrays

Passing individual Passing an entire


elements array

Passing Data Passing


Values addresses

One dimensional arrays for inter-function communication

6.1 Passing individual elements:


 The individual elements of an array can be passed to a function either
by their addresses or their data values.
6.1.1 Passing Data Values:
 The individual elements can be passed in the same manner as we
pass variables of any other data type.
 The condition is just that the data type of the array element must
match the type of the function parameter.
//passing individual array elements to a function

main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
func(arr[3]);
}
void func(int num)
{
printf(“%d”, num);
}

EXPLANATION:
 In the above example, only one element of the array is passed to the
called function.
 This is done by using the index expression.
 So arr[3] actually evaluates to a single integer value.

6.1.2 Passing Addresses:


 We can pass the address of an individual array element by preceding
the address operator ( & )to the element’s indexed reference.
 Therefore, to pass the address of the 4th element of the array to the
called function, we will write &arr[3].
 In the called function the value of the array element must be accessed
using the indirection ( * ) operator.
// passing individual array elements to function

Main()
{
Int arr[5]={ 1, 2, 3, 4,5 };
Fun(&arr[3]);
}
Void fun(int *num)
{ Printf(“%d”,num);
}
6.2 Passing The Entire Array:
 The array name refers to the first byte of the array in memory.
 The address of rest of the elements in the array can be calculated
using the array name and the index value of the element.
 Therefore when we need to pass an entire array to a function, we can
simply pass the name of the array.

// passing entire array to a function


main()
{
int arr[5]= { 1, 2, 3, 4,5 };
func(arr);
}
void func(int arr[5])
{
int i;
for(i=1;i<5;i++)
printf(“ %d”,arr[i]);
}
6 SAMPLE PROGRAMS:

1 Write a program to read and display n numbers using an array

// to read and display n numbers using an array

#include<stdio.h>

int main()

int i=0, n, arr[20];

printf(“ enter number of elements :”);

scanf(“%d”,&n);

for(i=0;i<n;i++)

printf(“\n arr[%d] = “, i );

scanf(“%d”, &arr[i] );

printf(“\n the array elements are “);

for(i=0; i<n; i++)

printf(“arr[%d] = %d \n“, i, arr[i] );

}
OUTPUT

Enter the number of elements: 4

arr[0] = 1

arr[1] = 2

arr[2] = 3

arr[3] = 4

the array elements are

arr[0] = 1

arr[1] = 2

arr[2] = 3

arr[3] = 4
2 . C Program to Calculate Average Using Arrays

This program takes n number of element from user (where, n is specified by


user), stores data in an array and calculates the average of those numbers.

Source Code to Calculate Average Using Arrays

#include <stdio.h>
int main()
{
int n, i;
float num[100], sum=0.0, average;
printf("Enter the numbers of data: ");
scanf("%d",&n);
while (n>100 || n<=0)
{
printf("Error! number should in range of (1 to 100).\n");
printf("Enter the number again: ");
scanf("%d",&n);
}
for(i=0; i<n; ++i)
{
printf("%d. Enter number: ",i+1);
scanf("%f",&num[i]);
sum+=num[i];
}
average=sum/n;
printf("Average = %.2f",average);
return 0;
}

Output

This program calculates the average if the number of data are from 1 to 100.
If user enters value of n above 100 or below 100 then, while loop is executed
which asks user to enter value of n until it is between 1 and 100.
3 C code to find largest and smallest number in an array

#include<stdio.h>
int main(){
int a[50],size,i,big,small;

printf("\nEnter the size of the array: ");


scanf("%d",&size);
printf("\nEnter %d elements in to the array: ", size);
for(i=0;i<size;i++)
scanf("%d",&a[i]);

big=a[0];
for(i=1;i<size;i++){
if(big<a[i])
big=a[i];
}
printf("Largest element: %d",big);

small=a[0];
for(i=1;i<size;i++){
if(small>a[i])
small=a[i];
}
printf("Smallest element: %d",small);

return 0;
}

Sample Output:
Enter the size of the array: 4
Enter 4 elements in to the array: 2 7 8 1
Largest element: 8
Smallest element: 1
/*
Program to Illustrate the Concept of Passing 1-D Array to
Function
Program to Find Largest from an Array
*/
#include <stdio.h>
#define SIZE 50
int big(int [], int);
main()
{
int a[SIZE], n, i, b;
printf("\nEnter size of array: ");
scanf("%d", &n);
printf("\nEnter elements:\n");
for (i=0; i<n; i++)
scanf("%d", &a[i]);
b = big(a, n);
printf("\nLargest number: %d", b);
getch();
}
int big(int a[], int n)
{
int b, i;
b = a[0];
for (i=0; i<n; i++)
if (a[i] > b)
b = a[i];
return b;
}

TWO- DIMENSIONAL ARRAYS


1.Introduction:
 ONE Dimensional array is organized linearly and only in one direction,
but sometimes we need to store data in the form of matrices or tables.
 A two dimensional array is specified using two subscripts(indexes)
where one index denotes rows and the other index denotes colum.
First
Dime
nsion

Second Dimension
2 Declaration of 2-Dimensional Arrays:

 Similar to one dimensional arrays, two dimensional arrays must be


declared before being used.
 The declaration statement tells the compiler the name of the array,
the data type of each element in the array, and the size of each
dimension.

SYNTAX:
Data_type array_name[row_size][column_size];

Therefore, a two-dimensional m X n array is an array that contains


m X n data elements and each element is accessed using two
subscripts, I and j where i<=m and j<=n.

For example, if we want to store the marks obtained by 3 students in


5 different subjects, then we can declare a two-dimensional array as
int marks[3][5];
Row/col Column 0 Column 1 Column 2 Column 3 Column 4
umns
Row 0 Marks[0][0] Marks[0][1] Marks[0][2] Marks[0][3] Marks[0][4]
Row 1 Marks[1][0] Marks[1][1] Marks[1]2] Marks[1]3] Marks[1][4]
Row 2 Marks[2][0] Marks[2][1] Marks[2][2] Marks[2][3] Marks[2][4]

Two dimensional array

EXPLANATION:
 A two dimensional array called marks declared that has m(3) rows
and n(5) columns.
 The first element of the array is denoted by marks[0][0], the second
element as marks[0][1] and so on.
 marks[0][0] stores the marks obtained by the first student in the
first subject, marks[1][0] stores the marks of the second student
in the first subject, and so on.
2.1 CALCULATION OF ADDRESS:
 the computer stores the base address and the address of the other
elements is calculated using the following formula
Address (A [I] [J] = BA + w { M ( J – 1 ) + ( I - 1 ) }
If the array elements are stored in column major order.
And
Address (A [I] [J] = BA + w { N ( I – 1 ) + ( J - 1 ) }
If the array elements are stored in row major order.

 Where w is the number of words stored per memory location,


M is the number of columns,
N is the number of rows,
I and J are the indexes of the array element,
And BA is the base Address.
Example:

Consider a 20 X 5 two dimensional array marks which has Base


Address = 1000
Number of words per memory location of the array =2
Now compute the address of the element marks[18,4]
Assuming that the elements are stored in row major order

SOLUTION:

Address A [I] [J] = BA + w { N ( I – 1 ) + ( J - 1 ) }

Address (marks[18,4])

= 1000 + 2 { 5 ( 18 – 1 ) + ( 4 – 1 ) }
= 1000 + 2 { 5 (17) + 3 }
= 1000 + 2 (88)
= 1176
3 INITIALIZATION OF TWO-DIMENSIONAL ARRAYS :

A two dimensional array is initialized in the same way as a one-


dimensional array.
int marks [2] [3] = { 90, 87, 78, 68, 62, 71 };
The initialization of a two- dimensional array is done row by row.
The above statement can also be written as
int marks [2] [3] = { { 90, 87, 78 },{ 68, 62,71 } };
The given two- dimensional array has 2 rows and 3 columns.

marks [0] [0] = 90 marks[0] [1]= 87


marks [0] [2] = 78 marks[1] [0]= 68
marks[1] [1] = 62 marks[1] [2]= 71

4 ACCESSING THE ELEMENTS:


 The elements in a multi dimensional array are stored in contiguous
memory locations.
 While accessing the elements, the last index varies most and the first
varies least.
 In case of single dimensional array we use single for to access.
 Since, a two dimensional array contains two indexes we will use two
for loops to access the elements.
 The first for loop indicates each row in the 2d array,
where as the second for loop indicates columns.
 We can assign individual elements of a two dimensional array
Marks [1] [2] = 79;
Marks [1] [2] = marks[1] [1] + 15;
 In order to input the values from the keyboard, you must use the
following code:
// to input the values from the keyboard
for(i=0; i<2; i++ )
for (j=0;j<2;j++)
scanf(“ %d”, &arr [i] [j] );
Example:

// to print the elements of a 2d array


#include<stdio.h>
main()
{
int arr[2] [2] = { 12, 34, 56, 32 };
int i, j;
for(i=0; i<2; i++ )
{
printf ( “ \n “ ) ;
for ( j=0; j<2; j++ )
printf ( “ %d “, arr[i] [j] );
}
return 0;
}
4.1 OPERATIONS ON TWO DIMENSIONAL (2D) ARRAYS:

We can perform the following operations on a two dimensional array:


Transpose: transpose of a m X n matrix A is given as a n X m matrix B
where,
B ( i, j ) = A ( j, i )
Sum: Two matrices that are compatible with each other can be added
together thereby storing the result in the third matrix. Two matrices are
said to be compatible when they have the same number of rows and
columns.
Elements of the matrices can be added by writing:
C ( i, j ) = A ( i, j ) + B ( i, j )
Difference: Two matrices that are compatible with each other can be
subtracted thereby storing the result in the third matrix. Two matrices are
said to be compatible when they have the same number of rows and
columns.
Elements of the matrices can be subtracted by writing:
C ( i, j ) = A ( i, j ) – B ( i, j )
Product: Two matrices can be multiplied with each other if the number of
columns in the first matrix is equal to the number of rows in the second
matrix. Therefore, m X n matrix A can be multiplied with a p X q matrix if
n=q.
Elements of the matrices can be multiplied by writing:
C ( i, j ) = ∑ A ( i, k ) B ( j, k ) for k = 1 to k < n

5 TWO-DIMENSIONAL ARRAYS FOR INTER-FUNCTION COMMUNICATION

 There are three ways of passing parts of the two-dimensional array to


a function (process).
 First, we can pass individual elements of the array. This is exactly
same as we passed element of a one-dimensional array.
 Second, we can pass a single row of the two-dimensional array. This is
equivalent to passing the entire one-dimensional array to a function.
This has already been discussed in the previous section.
 Third, we can pass the entire two-dimensional array to the function.
The following figure shows the three ways of using two-dimensional
arrays for inter-function, interprocess communication.
2d array for inter-function
communication

Passing individual Passing a row Passing an entire 2D


elements array

2d array for inter-function communication

5.1 Passing a row:


 A row of a two dimensional array can be passed by index in the
array name with the row number.
 When we send a single row of a two dimensional array, then the
called function receives a one dimensional array.

// passing a row
main()
{
int array[2][3] = { { 1, 2, 3 } , { 4, 5, 6} } ;
func ( array[1] );
}

void func ( int array[ ] )


{
int i;
for( i=0; i<5; i++ )
printf (“ %d “, array[i] * 10);
}
5.2 Passing an entire 2D array:

 To pass a two dimensional array to a function, we use the array


name as the actual parameter.
 This is similar to the one dimensional array .
 The parameter in the called function must indicate that the
array has two dimensions.

6. MULTI DIMENSIONAL ARRAYS:

 A multi dimensional array in simple terms is an array of arrays.


 Like we have one index in a 1 Dimensional array, two indices in a 2D
array, in the same way we have n indices in a n dimensional array or
multi dimensional array.
 Conversely, an n dimensional array is specified using n indices.
 An n dimensional m1 X m2 X ……. Mn array is a collection
m1 * m2 * ….,,,,,,,,,,,,,mn elements.
 In a multi dimensional array, a particular element is specified by
using n subscripts or indices as
A[ I1] [I2]……..[In],
where I1<=M1 I2<=M2………….In<=Mn
 A Multi Dimensional Array can contain as many indices as needed
and the requirement of the memory increases with the number of
indices used.

7. Sample Programs :
Program :

#include<stdio.h>
#include<conio.h>

void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k;
int sum=0;
clrscr();
printf("nEnter First Matrix : n");

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}

printf("nEnter Second Matrix:n");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
}

printf("The First Matrix Is:n");

for(i=0;i<3;i++)//print the first matrix


{
for(j=0;j<3;j++)
printf(" %d ",a[i][j]);
printf("n");
}

printf("The Second Matrix Is:n");

for(i=0;i<3;i++) // print the second matrix


{
for(j=0;j<3;j++)
printf(" %d ",b[i][j]);
printf("n");
}

for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
{
sum = 0;
for(k=0;k<=2;k++)
sum = sum + a[i][k] * b[k][j];
c[i][j]=sum;
}

printf("nMultiplication Of Two Matrices :nn");


for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
printf(" %d ",c[i][j]);
printf("n");
}

getch();
}

Steps :

Dimension of Matrix 1 : 1 X 3
Dimension of Matrix 2 : 3 X 2

Multiplication is Possible iff -

No. of Columns of Matrix 1 = No of Columns of Matrix 2

Resultant Matrix Will of Dimension-

c[No. of Rows of Mat1][No. of Columns of Mat2]


Steps 1 :

Evaluate : 1 X 2 = 2
Evaluate : 4 X 5 = 20
Evaluate : 6 X 7 = 22
-------------------------
Add : 64 ///c[0][0]

Step 2 :

Evaluate : 1 X 3 = 3
Evaluate : 4 X 8 = 40
Evaluate : 6 X 9 = 54
-------------------------
Add : 89 ///c[0][1]

Programmable Implementation :
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
{
sum = 0;
for(k=0;k<=2;k++)
sum = sum + a[i][k] * b[k][j];
c[i][j]=sum;
}
»
// to display 3 X 3 matrix
#include<stdio.h>
#include<conio.h>
void main()
{
int a[3][3],i,j;
clrscr();
printf("enter the elements\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&a[i][j]);
}
}
printf("matrix\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
printf("%d",a[i][j]);
}
printf("\n");
}
getch();
}

C program for addition of two matrices

#include<stdio.h>
#include<conio.h>

void main()
{
int i,j,a[10][10],b[10][10],c[10][10],m1,n1,m2,n2;

/* m - Number of rows
n - Number of Columns */

clrscr();

printf("nEnter the number of Rows of Mat1 : ");


scanf ("%d",&m1);
printf("nEnter the number of Columns of Mat1 : ");
scanf ("%d",&n1);

/* Accept the Elements in m x n Matrix */

for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
{
printf("Enter the Element a[%d][%d] : ",i,j);
scanf("%d",&a[i][j]);
}

// ------------------------------------------

printf("nEnter the number of Rows of Mat2 : ");


scanf ("%d",&m2);

printf("nEnter the number of Columns of Mat2 : ");


scanf ("%d",&n2);

/* Before accepting the Elements Check if no of


rows and columns of both matrices is equal */

if ( m1 != m2 || n1 != n2 )
{
printf("nOrder of two matrices is not same ");
exit(0);
}

// ------ Terminate Program if Orders are unequal


// ------ exit(0) : 0 for normal Termination

/* Accept the Elements in m x n Matrix */

for(i=0;i<m2;i++)
for(j=0;j<n2;j++)
{
printf("Enter the Element b[%d][%d] : ",i,j);
scanf("%d",&b[i][j]);
}

// ------------------------------------------

/* Addition of two matrices */


for(i=0;i<m1;i++)
for(j=0;j<n1;j++)
{
c[i][j] = a[i][j] + b[i][j] ;
}

/* Print out the Resultant Matrix */

printf("nThe Addition of two Matrices is : n");

for(i=0;i<m1;i++)
{
for(j=0;j<n1;j++ )
{
printf("%dt",c[i][j]);
}
printf("n");
}

getch();
}

Output

Enter the number of Rows of Mat1 : 3


Enter the number of Columns of Mat1 : 3
Enter the Element a[0][0] : 1
Enter the Element a[0][1] : 2
Enter the Element a[0][2] : 3
Enter the Element a[1][0] : 2
Enter the Element a[1][1] : 1
Enter the Element a[1][2] : 1
Enter the Element a[2][0] : 1
Enter the Element a[2][1] : 2
Enter the Element a[2][2] : 1

Enter the number of Rows of Mat2 : 3


Enter the number of Columns of Mat2 : 3
Enter the Element b[0][0] : 1
Enter the Element b[0][1] : 2
Enter the Element b[0][2] : 3
Enter the Element b[1][0] : 2
Enter the Element b[1][1] : 1
Enter the Element b[1][2] : 1
Enter the Element b[2][0] : 1
Enter the Element b[2][1] : 2
Enter the Element b[2][2] : 1

The Addition of two Matrices is :


246
422
242

Note : 2-D array needs two nested for loops


KEEP IN MIND:
1. One Matrix can be added with another only if the order of
both matrices is Equal
2. No of rows of MAT-1 = No of rows of MAT-2
3. No of col of MAT-1 = No of col of MAT-2
4. During addition a[0][0] is added with b[0][0] and result is
stored in c[0][0]
Special Note :
We required two ‘for loops’ (nested) for following Perpose :
1. Accepting Matrix
2. Displaying Matrix
3. Manipulating Matrix
4. Performing Different Operations on Matrix

Algorithm:
Addition of two matrices:
Rule: Addition of two matrices is only possible if
both matrices are of same size.
Suppose two matrices A and B is of same size m X n
Sum of two matrices is defined as
(A + B)ij = Aij + Bij
Where 1 ≤ i ≤ m and 1 ≤ j ≤ n

For example:
Suppose two matrices A and B of size of 2 X 3 is as
follow:
Program to find Transpose of Given Square Matrix

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],m,i,j,temp;
/* actual size of matrix is m*n
i,j - for scanning of array
temp - for interchanging of a[i][j] and a[j][i] */

printf("n Enter the size of matrix :");


scanf("%d",&m);

/* Reading elements of matrix */

printf("n Enter the values a:");

for(i=0;i<m;i++)
for(j=0;j<m;j++)
scanf("%d",&a[i][j]);

//to print original square matrix

printf("nGiven square matrix is");

for(i=0;i<m;i++)
{
printf("n");
for(j=0 ; j 〈 m ; j++)
printf("%dt",a[i][j]);
}
/* Find transpose */

for(i=1;i<m;i++)
for(j=0;j<i;j++)
{
temp=a[i][j];
a[i][j]=a[j][i];
a[j][i]=temp;
}
/* printing of all elements of final matrix */

printf("nTranspose matrix is :");


for(i=0;i 〈 m;i++)
{
printf("n");
for(j=0;j<m;j++)
printf("%dt",a[i][j]);
}
getch();
}

BY:
MR. D.SRINIVAS RAO
ASST.,PROF.
DEPT OF IT
GITAM UNIVERSITY
HTP CAMPUS

You might also like