PoP Arrays 2023

You might also like

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

Principles of Programming using C 2023

MODULE -3 ARRAYS
INTRODUCTION
•An array is a collection of similar data elements.
•These data elements have the same data type.
•The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript).
•Declaring an array means specifying three things:
The data type- what kind of values it can store ex, int, char, float
Name- to identify the array
The size- the maximum number of values that the array can hold
•Arrays are declared using the following syntax:
type name[size];

ACCESSING ELEMENTS OF THE ARRAY


To access all the elements of the array, you must use a loop. That is, we can access all
the elements of the array by varying the value of the subscript into the array. But
note that the subscript must be an integral value or an expression that evaluates to
an integral value.

1 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

CALCULATING THE ADDRESS OF ARRAY ELEMENTS


Address of data element, A[k] = BA(A) + w( k – lower_bound)
Here, A is the array
k is the index of the element of 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, for example, size of int is 2.

STORING VALES IN ARRAYS

Initialization of Arrays :Arrays are initialized by writing,


General format:
type array_name[size]={list of values};
Example:
int marks[5]={90, 82, 78, 95, 88};
2 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

CALCULATING THE LENGTH OF THE ARRAY


Length = upper_bound – lower_bound + 1
Where, upper_bound is the index of the last element and lower_bound is the
index of the first element in the array

Here, lower_bound = 0, upper_bound = 7, therefore, length = 7 – 0 + 1 = 8


OPERATIONS ON ARRAYS
There are a number of operations that can be performed on arrays. These
operations include the following:
 Traversing an array
 Inserting an element in an array
 Deleting an element in an array
 Merging two arrays
 Searching an element in an array
 Sorting an array in ascending or descending order

Traversing an Array
Traversing an array means accessing each and every element of the array for a
specific purpose.

3 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Algorithm for Traversing an Array:

Step 01: Start


Step 02: [Initialize counter variable. ] Set i = LB.

Step 03: Repeat for i = LB to UB.


Step 04: Apply process to arr[i].
Step 05: [End of loop. ]
Step 06: Stop

Variables used:
i : Loop counter or counter variable for the for loop.
arr : Array name.
LB : Lower bound. [ The index value or simply index of the first element of an array is
called its lower bound ]
UB : Upper bound. [ The index of the last element is called its upper bound ]

4 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Flowchart for Traversing an Array:

Implementation in C:
writing a program in C to perform traverse operation in array

void main()
{
int i, size;
int arr[] = {1, -9, 17, 4, -3}; //declaring and initializing array "arr"

size = sizeof(arr)/sizeof(arr[0]); //sizeof(arr) will give 20 and


sizeof(arr[0]) will give 4

5 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

printf("The array elements are: ");

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


printf("\narr[%d]= %d", i, arr[i]);

}
Output:
The array elements are:
arr[0]= 1
arr[1]= -9
arr[2]= 17
arr[3]= 4
arr[4]= -3

Write a program to read n number of values in an array and display it in reverse


order
#include <stdio.h>

void main()
{
int i,n,a[100];

printf("\n\nRead n number of values in an array and display it in reverse


order:\n");
printf("------------------------------------------------------------------------\n");

printf("Input the number of elements to store in the array :");


scanf("%d",&n);

printf("Input %d number of elements in the array :\n",n);


for(i=0;i<n;i++)
{
6 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

printf("element - %d : ",i);
scanf("%d",&a[i]);
}
printf("\nThe values store into the array are : \n");
for(i=0;i<n;i++)
{
printf("% 5d",a[i]);
}

printf("\n\nThe values store into the array in reverse are :\n");


for(i=n-1;i>=0;i--)
{
printf("% 5d",a[i]);
}
printf("\n\n");
}

INSERTING ELEMENTS IN AN ARRAY


We can insert the elements wherever we want, which means we can insert either at
starting position or at the middle or at last or anywhere in the array.
After inserting the element in the array, the positions or index location is increased
but it does not mean the size of the array is increasing.
The logic used to insert element is −
 Enter the size of the array

7 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

 Enter the position where you want to insert the element


 Next enter the number that you want to insert in that position

Final array should be printed using for loop.

Write a C program for INSERTING ELEMENTS IN THE MIDDLE OF AN ARRAY


#include<stdio.h>
int main(){
int student[40],pos,i,size,value;
printf("enter no of elements in array of students:");
scanf("%d",&size);

8 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

printf("enter %d elements are:",size);


for(i=0;i<size;i++)
scanf("%d",&student[i]);
printf("enter the position where you want to insert the element:");
scanf("%d",&pos);
printf("enter the value into that poition:");
scanf("%d",&value);
for(i=size-1;i>=pos-1;i--)
student[i+1]=student[i];
student[pos-1]= value;
printf("final array after inserting the value is");
for(i=0;i<=size;i++)
printf("%d",student[i]);
return 0;
}

9 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Insert a number in an array sorted in ascending order


#include<stdio.h>
int main(){
int i, n, arr[100], num, pos=0;
printf("Enter the size of array : ");
scanf("%d",&n);
printf("Enter the elements of the array : ");
for (i = 0; i < n; i++) {
scanf("%d",&arr[i]);
}
printf("Enter the element to be entered : ");
scanf("%d",&num);
/*Find position where elements should be entered.*/
for(i=0;i<n;i++){
if(arr[i]<num){
pos++;
}else{
break;
}
}
printf("%d should be entered at position %d",num,pos);
/* Execute a loop to move all elements right by 1 position having
index greater than position where to insert element */
for(i=n-1;i>=pos;i--) {
arr[i+1] = arr[i];
}
// Insert element at given position
arr[pos] = num;
// Finally print new array after insertion of new element
printf("\nThe new array is : ");
for(i=0;i<=n;i++) {
printf("%d ", arr[i]);
}
return 0;
}
Output:

Enter the size of array :

10 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Enter the elements of the array :


16
25
29
37
55
Enter the element to be entered :
35
Output:
35 should be entered at position 3

The new array is :


16 25 29 35 37 55

Write a c program for deleting elements from an array


 To delete a specific element from an array, a user must define the position from
which the array's element should be removed.
 The deletion of the element does not affect the size of an array. Furthermore, we
should also check whether the deletion is possible or not in an array.
 For example, suppose an array contains seven elements, arr[] = {10, 25, 14, 8, 12,
15, 5); and the user want to delete element 8. So, first, the user must define the
position of the 8th element, which is the 4th, and then check whether the deletion is
possible or not.
 The position of the particular element should not be more than the total elements of
an array. Here, we have 7 elements in an array, and the user wants to delete the
8th position element, which is impossible.

Steps to remove an element from an array


Following is the steps to remove a particular element from an array in C programming.

Step 1:Input the size of the array arr[] using num, and then declare the pos variable to
define the position, and i represent the counter value.

Step 2: Use a loop to insert the elements in an array until (i < num) is satisfied.

Step 3:Now, input the position of the particular element that the user or programmer
wants to delete from an array.

11 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Step 4:Compare the position of an element (pos) from the total no. of elements (num+1).
If the pos is greater than the num+1, the deletion of the element is not possible and jump
to step 7.

Step 5:Else removes the particular element and shift the rest elements' position to the left
side in an array.

Step 6: Display the resultant array after deletion or removal of the element from an array.

Step 7: Terminate or exit from the program.

Example 1: Program to remove an element from an array using for loop


Let's create a program to delete an element from an array using for loop in the C
programming language.

/* program to remove the specific elements from an array in C. */


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

int main ()
{
// declaration of the int type variable
int arr[50];
int pos, i, num; // declare int type variable
printf (" \n Enter the number of elements in an array: \n ");
scanf (" %d", &num);

printf (" \n Enter %d elements in array: \n ", num);

// use for loop to insert elements one by one in array


for (i = 0; i < num; i++ )
{ printf (" arr[%d] = ", i);
scanf (" %d", &arr[i]);
}

// enter the position of the element to be deleted


printf( " Define the position of the array element where you want to delete: \n ");
scanf (" %d", &pos);

// check whether the deletion is possible or not


12 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

if (pos >= num+1)


{
printf (" \n Deletion is not possible in the array.");
}
else
{
// use for loop to delete the element and update the index
for (i = pos - 1; i < num -1; i++)
{
arr[i] = arr[i+1]; // assign arr[i+1] to arr[i]
}

printf (" \n The resultant array is: \n");

// display the final array


for (i = 0; i< num - 1; i++)
{
printf (" arr[%d] = ", i);
printf (" %d \n", arr[i]);
}
}
return 0;
}

Output:
Enter the number of elements in an array:
8

Enter 8 elements in array:


arr[0] = 3
arr[1] = 6
arr[2] = 2
arr[3] = 15
arr[4] = 10
arr[5] = 5
arr[6] = 8
arr[7] = 12
Define the position of the array element where you want to delete:
5

13 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

The resultant array is:


arr[0] = 3 arr[1] = 6 arr[2] = 2 arr[3] = 15 arr[4] = 5 arr[5] = 8
arr[6] = 12

 In the above program, we input 8 elements for an array arr[] from the user. After
that, the user enters the position of the particular element is 5.
 And then, we checked the defined position by the If statement (if (pos > num + 1));
 Here, 5 is less than the (num+1). So the condition is false, and it executes the else
block to remove the 5th position of the element is 10 using for loop and then prints
the resultant array.

Another example for deletion of an array element from an array


 Deletion operation in Array or delete an element from an Array simply
means, Removing an existing element from a specific position of an array.
How do you delete an element from an array in C
delete an element from a specific position of an array step-by-step:

Variables we are using here:

1. a : Name of the array.


2. size : Size of the array (i.e., total number of elements in the array)
3. i : Loop counter or counter variable for the for loop.
4. pos : The position from where we wish to delete the element.

The following algorithm deletes a data element from a specific position pos (position specified
by the programmer) of a linear array ‘a‘.

Algorithm to Delete an element from an Array:


 Step 01: Start
 Step 02: [Initialize counter variable. ] Set i = pos - 1
 Step 03: Repeat Step 04 and 05 for i = pos - 1 to i < size
 Step 04: [Move ith element backward (left). ] set a[i] = a[i+1]

14 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

 Step 05: [Increase counter. ] Set i = i + 1


 Step 06: [End of step 03 loop. ]
 Step 07: [Reset size of the array. ] set size = size - 1
 Step 08: Stop
In the above algorithm, step 2 to step 5 shifts (moves) each such element one location (position)
backward (left) whose position is greater than the position of the element which we wish to
delete.
The next step, Step 6, ends the loop.
And, at the last step, Step 7, decrements (reduces) the size of the array by one.
Now, few questions might be arising in your mind.
 Why we are shifting (moving) each such element one position backward whose position
is greater than the position of the element which we wish to delete?
 And,Why we are reducing the size of the array by one? Right?
The answer of the above two questions are very straightforward,

 It’s only because, When you shift an element one position backward (left), the element
that already present in that position (position where you are shifting the element) gets
changed. And the value that you are shifting towards left gets copied or overwritten at
that position.

 Subsequently, after shifting all such values which are present right to the element which
we wish to delete, When we reach to the position from where we have to delete the
element then, we don’t shift the element which is present at that position or all such
elements which are present left from that position to the left of it backward.

 And, since we are shifting only those elements which are present ahead (right) from that
position.

 So at the end, the value of that position will change and the value next to it will come at
that position. And in that case the already existing value will be removed .

 As a result, the size of the array will now be reduced by one, due to the removal of one
element from the array.

15 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Visual Representation

16 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

// writing a program in C to delete an element from an array


void main()
{
int i, size, pos;
int a[] = {2, 4, 6, 8, 12};

size = sizeof(a)/sizeof(a[0]);

printf("The array elements before deletion operation:\n");

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


printf("a[%d] = %d\n", i, a[i]);

printf("\nEnter the position from where you wish to delete the element: ");
scanf("%d", &pos);

printf("\nThe array elements after deletion operation are:\n");

for(i = pos - 1; i < size; i++)


a[i] = a[i+1];

size = size - 1;

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


printf("a[%d] = %d\n", i, a[i]);

}
Output:
The array elements before deletion operation:
a[0] = 2
a[1] = 4
a[2] = 6
a[3] = 8
a[4] = 12

Enter the position from where you wish to delete the element: 3

The array elements after deletion operation are:


a[0] = 2
17 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

a[1] = 4
a[2] = 8
a[3] = 12

Merging Two Arrays


Merging two arrays in c is similar to Concatenating or combining two arrays into a single array.
For example, if the first array has four elements and the second array has five elements, the
resulting array has nine elements.
Example:
First Array = [1, 2, 3, 4, 5]
Second Array = [6, 7, 8, 9, 10]
Merged Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Write a C program to merge two sorted array elements into a single array.

Problem Solution

1. Create two arrays of some fixed size and define their elements in sorted fashion.
2. Take two variables i and j, which will be at the 0th position of these two arrays.
3. Elements will be compared one by one using i and j in for loop, and whichever element is
smaller than the other, that element will get inserted to final array and the position(either i or j)
will move by one, whereas the other array’s track position will remain in that same place.
4. Above work will be done till we reach the end of either array. After that, one of the array
whose elements are still to be added, its elements will get straightaway added to the final array.

Method 1: Merge Two Sorted Arrays in C using For Loop (Naive Approach)
In this approach, we will use a for loop to iterate through the array and merge the two arrays.

Example:
First Array = [12, 18, 23]
Second Array = [13, 19, 27]
Merged Array = [12, 13, 18, 19, 23, 27]

// C Program To Merge Two Unsorted Arrays


// using Quaint Methodology
#include <stdio.h>
int main()
{

18 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

int arr1size = 5, arr2size = 5, arr_resultsize, i, j;

// elements of first Array


int a[5] = { 1, 2, 3, 4, 5 };

// elements of Second Array


int b[5] = { 6, 7, 8, 9, 10 };

// resultant Array Size Declaration


arr_resultsize = arr1size + arr2size;
int c[arr_resultsize];
// copying array 1 elements into an array
for (i = 0; i < arr1size; i++)
{
c[i] = a[i];
}

// copying array 2 elements into an array


for (i = 0, j = arr1size; j < arr_resultsize && i < arr2size; i++, j++)
{
c[j] = b[i];
}

// Array Elements After Merging


for (i = 0; i < arr_resultsize; i++)
{
printf("%d ", c[i]);
}
return 0;
}

Output

1 2 3 4 5 6 7 8 9 10

Write a program to merge two sorted arrays

Method 1: Merge Two Sorted Arrays in C using For Loop (Naive


Approach)
In this approach, we will use a for loop to iterate through the array and merge the two arrays.

19 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Example:
First Array = [12, 18, 23]
Second Array = [13, 19, 27]
Merged Array = [12, 13, 18, 19, 23, 27]

/*
* C Program to merge two sorted arrays using for loop
*/

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
int i, n, j, k;
printf("Enter the size of the first array: ");
scanf("%d", &n);
int arr1[n];
printf("Enter the elements of the first array: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &arr1[i]);
}
printf("Enter the size of the second array: ");
scanf("%d", &k);
int arr2[k];
printf("Enter the elements of the second array: \n");
for (j = 0; j < k; j++)
{
scanf("%d", &arr2[j]);
}
int arr3[n + k];
i = j = 0;
int in;
for (in = 0; in < n + k; in ++)
{
if (i < n && j < k)
{
if (arr1[i] < arr2[j])
{
arr3[in] = arr1[i];
20 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

i++;
}
else
{
arr3[in] = arr2[j];
j++;
}
}
else if (i < n)
{
arr3[in] = arr1[i];
i++;
}
else
{
arr3[in] = arr2[j];
j++;
}
}
printf("The merged array is: \n");
for (in = 0; in < n + k; in++)
{
printf("%d ", arr3[in]);
}
printf("\n");
return 0;
}

Output:
Enter the size of the first array: 3
Enter the elements of the first array:
12
18
23
Enter the size of the second array: 3
Enter the elements of the second array:
13
19
27
The merged array is:
12 13 18 19 23 27

21 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Searching for an value in an array


Searching is the process of finding an item with the specified properties from a collection of
items. The items may be stored as records in a database or a simple data element in the array,
text in files, nodes in trees, vertices, and edges in graphs or they may be elements of other
search spaces.
Why do we need searching?
Searching is one of the computer science algorithms. You know that today’s modern computers
store a lot of information. To read this information proficiently, we need very efficient
searching algorithms.
There are certain ways of organizing data that improves the searching process. That means If we
keep the data in proper order it is easy to search the required elements. Sorting is one of the
techniques for making the elements order. In this post, we will see different searching
algorithms.
Types of Searching
The following are the types of searching available in computer science.
 Linear Search
 Binary Search

Linear Search
A linear search or sequential search is a method for finding an element within a list. It
sequentially checks each element of the list until a match is found or the whole list has been
searched.
Or
Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.

#include<stdio.h>

#include<stdlib.h>

void main( )
{
int n, a[100], i, key,loc;
loc=-1;
printf("Enter the size of the array\n");
scanf("%d",&n);
printf("Enter the elements of array in sorted order\n");
for(i=0;i<n;i++)
22 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

scanf("%d",&a[i]);
printf("Enter the key element to be searched\n");
scanf("%d",&key);
for(i=0;i<n;i++)
{
if(key == a[i]
{
loc=i+1;
break;
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc);else
printf("The search is unsuccessful\n");
}

Binary Search
 Binary search works only on a sorted set of elements.To use binary search on a
collection, the collection must first be sorted.

 The array is divided into two parts,compared with middle element if it is not successful,
then it is compared whether it is lesser or greater than middle element. If it is lesser,
search is done towards left part else right part.
#include<stdio.h>
#include<stdlib.h>
void main( )
{
int n, a[100], i, key, loc, high, low, mid; loc=-1;
printf("Enter the size of the array\n"); scanf("%d",&n);
printf("Enter the elements of array in sorted order\n"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter the key element to be searched\n"); scanf("%d",&key);
low=0; high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
loc = mid+1; break;

23 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

}
else
{
if(ele<a[mid])
high=mid-1;

else
low=mid+1;

}
}
if(loc>=0)
printf("The element %d is found at %d \n",ele,loc); else
printf("The search is unsuccessful\n");
}

Two-Dimensional Arrays: A list of items can be given one variable name using two
subscripts and such a variable is called a single subscripted variable or one dimensional
array.
 It consists of both rows and columns. Ex: Matrix.

Declaration of Two-Dimensional Array: Here is general syntax for array declaration along
with examples.

Syntax: data_type array_name[row_size][column_size];

Examples: int marks[4][4];


float city_temper[3][3];

Note: Declaration and definition specify the data type of


array, its name and size.

24 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

Initialization of Two-Dimensional Array: After array is declared, next is storing values in


to an array is called initialization. There are two types of array initialization:

1. Compile-time initialization
2. Run-time initialization

1. Compile time initialization: If we assign values to the array during declaration it is


called compile time initialization. Following are the different methods of compile time
initialization.

Syntax: data_type array_name[size]={list of values};


Examples: int marks[3][4]={ 1,2,3, 4, 5, 6, 7,8,9,10,11,12};
float city_temper[2][2]={29.5, 30.7, 35.6, 45.7};

Note: in the above examples we are storing values in marks array and
temperature array respectively. The pictorial representation is also given
below
 After initialization the arrays appear as follows:

29.5 30.5
marks 1 2 3 4 city_temp
35.6 45.7
5 6 7 8

25 Dept. of CSE,CBIT,KOLAR
Principles of Programming using C 2023

2. Run time initialization: Run time initialization is storing values in an arraywhen


program is running or executing.
Following example illustrates run time storing of values using scanf and for loop:
Example: printf(“Enter the marks”);

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


for(j=0;j<4;j++)
{
scanf(“ %d”, &marks[i][j]);
}
More Examples: Other way of initialization:

int a[ ][3]= { 0, 1, 2, 3,4,5,6,7,8};


int b[ ][4] ={1,2,3,4,5,6,7,8,9,10,11,12};

012 1234
a b
345 5678

67 8 9 10 11 12

Example for Invalid initialization

int A[3][ ]={1,2,3};


Note: Never have column size undeclared in two dimension array.

Write a program to print the elements of a 2D array.


#include<stdio.h>
#include<conio.h>
int main()
{
int arr[4][2] = {{1, 2}, {3, 4}, {5, 6}, {7, 8}};
int i, j;
printf("The Two-dimensional Array is:\n");
for(i=0; i<4; i++)
26 Dept. of CSE, CBIT,KOLAR
Principles of Programming using C 2023

{
for(j=0; j<2; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
getch();
return 0;
}
Output:

Allow the user to define the array size


#include<stdio.h>
#include<conio.h>
int main()
{
int arr[10][10], row, col, i, j;
printf("Enter Row Size of Array (max. 10): ");
scanf("%d", &row);
printf("Enter Column Size of Array (max. 10): ");
scanf("%d", &col);
printf("\nEnter %d Array Elements: ", row*col);
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
scanf("%d", &arr[i][j]);
}
printf("\nThe Array is:\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
getch();
return 0;
}

27 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

Output:
Enter Row Size of Array(max.10): 2
Enter column Size of Array(max.10): 4
Enter 10 Array Elements:
1 2 3 4 5 6 7 8 9 10

The Array is
1 2 3 4
5 6 7 8

Operations on Two Dimensional Arrays

Two dimentsional arrays can be used to implement the mathematical concept of matrices.
The following operations can be performed on m x n matrix

Transpose : Transpose of a m x n matrix A is given as a n x m matrix B where,


Bi,j = A j,i

Sum:Two matrices that are compatible (matching with number of rows and columns) with
each other can be added together thereby storing the result in the third matrix.

Ci,j=Ai,j + Bi,j

Difference: Two matrices that are compatible (matching with number of rows and columns)
with each other can be subtracted thereby storing the result in the third matrix.

Ci,j=Ai,j - Bi,j

Product : Two matrices can be multiplied with each othr if the number of columns in the first
matrix is equal to the number of rows in the second matrix.

Therefore m x n martrix A can be multiplied with a p xq matrix if n=p elements of the matrics
can be multipled by writing

Ci,j = 𝜀 𝐴𝑖, 𝑘 𝐵𝑘, 𝑗 𝑓𝑜𝑟 𝑘 = 1 𝑡𝑜 𝑘 < 𝑛

Write a program to transpose a 3 x 3 matrix


#include<stdio.h>
#include<conio.h>
int main()
{

28 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

int mat[10][10], rowSize, colSize, i, j, matTrans[10][10];


printf("Enter the Size of Row and Column: ");
scanf("%d%d", &rowSize, &colSize);
printf("\nEnter %d*%d Matrix Elements: ", rowSize, colSize);
for(i=0; i<rowSize; i++)
{
for(j=0; j<colSize; j++)
scanf("%d", &mat[i][j]);
}
printf("\nOriginal Matrix is:\n");
for(i=0; i<rowSize; i++)
{
for(j=0; j<colSize; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
// Transposing the Matrix.....
for(i=0; i<rowSize; i++)
{
for(j=0; j<colSize; j++)
matTrans[j][i] = mat[i][j];
}
printf("\nTranspose of Matrix is:\n");
for(i=0; i<colSize; i++)
{
for(j=0; j<rowSize; j++)
printf("%d ", matTrans[i][j]);
printf("\n");
}
getch();
return 0;
}

29 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

Write a program to input two mxn matrices and the calculate the sum of their corresponding elements
and store it in a third m x n matrix.
#include <stdio.h>

void main()
{
int arr1[50][50],brr1[50][50],crr1[50][50],i,j,n;

printf("\n\nAddition of two Matrices :\n");


printf("------------------------------\n");
printf("Input the size of the square matrix (less than 5): ");
scanf("%d", &n);

/* Stored values into the array*/


printf("Input elements in the first matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&arr1[i][j]);
}
}

printf("Input elements in the second matrix :\n");


for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("element - [%d],[%d] : ",i,j);
scanf("%d",&brr1[i][j]);
}
}
printf("\nThe First matrix is :\n");
for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",arr1[i][j]);
}

printf("\nThe Second matrix is :\n");


for(i=0;i<n;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",brr1[i][j]);
}
/* calculate the sum of the matrix */
for(i=0;i<n;i++)
30 Dept. of CSE, CBIT,KOLAR
Principles of Programming using C 2023

for(j=0;j<n;j++)
crr1[i][j]=arr1[i][j]+brr1[i][j];
printf("\nThe Addition of two matrix is : \n");
for(i=0;i<n;i++){
printf("\n");
for(j=0;j<n;j++)
printf("%d\t",crr1[i][j]);
}
printf("\n\n");
}

Sample Output:
Addition of two Matrices :
------------------------------
Input the size of the square matrix (less than 5): 2
Input elements in the first matrix :
element - [0],[0] : 1
element - [0],[1] : 2
element - [1],[0] : 3
element - [1],[1] : 4
Input elements in the second matrix :
element - [0],[0] : 5
element - [0],[1] : 6
element - [1],[0] : 7
element - [1],[1] : 8

The First matrix is :


1 2
3 4
The Second matrix is :
5 6
7 8
The Addition of two matrix is :
6 8
10 12

Program to find the product of two matrices


Explanation
In this program, we need to multiply two matrices and print the resulting matrix.

31 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

Product of two matrices


The product of two matrices can be computed by multiplying elements of the first row of the first matrix with
the first column of the second matrix then, add all the product of elements. Continue this process until each row
of the first matrix is multiplied with each column of the second matrix.

Consider above example, first element in resulting matrix prod[0,0] can be computed by multiplying first row of
first matrix i.e. (1, 3, 2) with first column of second matrix i.e. (2, 1, 1) and finally sum all the product of
elements i.e. (1*2) + (3*1) + (2*1) = 7. Similarly, second entry prod[0,1] can be computed by multiplying the
first row of the first matrix with the second column of the second matrix and sum all the product.

Two matrices can be multiplied if and only if they satisfy the following condition:

The number of columns present in the first matrix should be equal to the number of rows present in
the second matrix.

Suppose dimension of matrix A is p × q and matrix B is q × r, then the dimension of resulting matrix
will be p × r. Matrix multiplication can be represented as

Cij = Σ AikBkj

#include<stdio.h>
#include<stdlib.h>
int main( )
{
int m,n,p,q,row,col,k,a[3][3],b[3][3],c[3][3];
printf("Enter the order of matrix A\n");
scanf("%d%d",&m,&n);
printf("enter order of matrix B\n");
scanf("%d%d",&p,&q);
if(n!=p)
{
printf("Matrix Multiplication is not possible\n");exit(0);

32 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

printf("Enter the elements into matrix A\n");


for(row=0;row<m;row++)
{
for(col=0;col<n;col++)
{
scanf("%d",&a[row][col]);
}
}
printf("Enter the elements into matrix B\n");
for(row=0;row<p;row++)
{
for(col=0;col<q ;col++)
{
scanf("%d",&b[row][col]);
}
}
for(row=0;row<m;row++)
{
for(col=0;col<q;col++)
{
c[row][col]=0;
for(k=0;k<n;k++)
{
c[row][col]= c[row][col]+a[row][k]*b[k][col];
}
}
}
printf("The elements of matrix A are\n");
for(row=0;row<m;row++)
{
for(col=0;col<n;col++)
{
printf("%3d",a[row][col]);
}
33 Dept. of CSE, CBIT,KOLAR
Principles of Programming using C 2023

printf("\n");
}
printf("The elements of matrix B are\n");
for(row=0;row<p;row++)
{
for(col=0;col<q;col++)
{
printf("%3d",b[row][col]);
}
printf("\n");
}
printf("Product of Matrix A and B is\n");
for(row=0;row<m;row++)
{
for(col=0;col<q;col++)
{
printf("%3d",c[row][col]);
}

printf("\n");
}
}

Output:

Enter the order of matrix A


2 2
Enter the order of matrix B
2 2
Enter the elements into matrix A
12 3 4
Enter the elements into matrix B
5 6 7 8
Elements of matrix A are
1 2

34 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

3 4
Elements of matrix B are
5 6
7 8

Product of matrix A and B is


19 22
43 50

USING ARRAYS WITH FUNCTIONS:


In large programs that use functions we can pass Arrays as parameters. Two ways of
passing arrays to functions are:
1. Pass individual elements of array as parameter
2. Pass complete array as parameter

Let us take an example program that uses a function square( ) to calculate square of
numbers stored in an array. In this program each array element is passed one by one.

Example-1 cont’d:
Example-1 void square(int no )
int square(int);void
{
main( )

int sq;
{
sq=no*no; /*square is calculated*/
int num[5], i;

num[5] ={3,4, 8, 9, 10}; printf(“square is=%d ”, sq);

for(i=0; i<5; i++) }

square(num[i]);

} Output:

} Square is=9 16 64 81 100

35 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

This diagram clearly illustrates how each individual element of array num[ ] is passed to
function square through parameter no.

3 4 8 9 10
0 1 2 3 4 num[3]=9 no

num[1]=4 copied  no

num[0]=3 copied to no
num[2]=8 no

Next program illustrates how to pass an entire array to a function average( ) and
calculate average marks. First sum of all the elements of array marks

(i.e.35+65+75+95+85) is calculated and average is stored in a variable avg. value in avg


variable is returned to main( ) and stored in avg1

Example-2: Example-2 cont’d:

float average(int score[]); float average(int score[ ] )


void main( )
{
{
int i , sum=0;
int marks[5], i float avg;
float avg1; for(i=0; i<5;i++)
marks[5] ={35,65, 75, 95, 85}; {

avg1=average(marks); sum=sum+score[i];

printf(“average=%f”, avg1) }

} avg=sum/5;
return (avg);

}
Output:

average=71.000000

36 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

In the above example each value of array marks[ ] is copied to array scores[ ] as shown
below:
marks[0]=35 copied to scores[0]

marks[1]=65 copied to scores[1]

marks[2]=75 copied to scores[2]

marks[3]=95 copied to scores[3]

marks[4]=85 copied to scores[4]

using these values average is calculated:


(35+65+75+95+85)/5=

71.000000

Multi Dimensional Arrays: Multidimensional arrays can have three, four ormore
dimensions.
 A three-dimension array is an array of two dimensional arrays. It has row, column
and depth associated with it.
 Declaring multidimensional arrays
int table[3][5][4];

Here are two examples illustrating three-dimensional array declaration and


initialization

37 Dept. of CSE, CBIT,KOLAR


Principles of Programming using C 2023

Initializing Three-Dimensional Array: Initialization in a Three-Dimensional array is the


same as that of Two-dimensional arrays. The difference is as the number of dimensions
increases so the number of nested braces will also increase.
Method 1:
int x[2][3][4] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23};
Method 2(Better):
int x[2][3][4] =
{
{ {0,1,2,3}, {4,5,6,7}, {8,9,10,11} },
{ {12,13,14,15}, {16,17,18,19}, {20,21,22,23} }
};
Accessing elements in Three-Dimensional Arrays: Accessing elements in Three-
Dimensional Arrays is also similar to that of Two-Dimensional Arrays. The difference is we
have to use three loops instead of two loops for one additional dimension in Three-
dimensional Arrays.

// C program to print elements of Three-Dimensional Array

#include <stdio.h>

int main(void)
{
38 Dept. of CSE, CBIT,KOLAR
Principles of Programming using C 2023

// initializing the 3-dimensional array


int x[2][3][2] = { { { 0, 1 }, { 2, 3 }, { 4, 5 } },
{ { 6, 7 }, { 8, 9 }, { 10, 11 } } };

// output each element's value


for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
printf("Element at x[%i][%i][%i] = %d\n", i, j, k, x[i][j][k]);
}
}
}
return (0);
}
Output:
Element at x[0][0][0] = 0
Element at x[0][0][1] = 1
Element at x[0][1][0] = 2
Element at x[0][1][1] = 3
Element at x[0][2][0] = 4
Element at x[0][2][1] = 5
Element at x[1][0][0] = 6
Element at x[1][0][1] = 7
Element at x[1][1][0] = 8
Element at x[1][1][1] = 9
Element at x[1][2][0] = 10
Element at x[1][2][1] = 11
In similar ways, we can create arrays with any number of dimensions. However, the
complexity also increases as the number of dimensions increases. The most used
multidimensional array is the Two-Dimensional Array.

Applications of Arrays
 Arrays are widely used to implement mathematical vectors, matrices and other kinds of
rectangular tables.
 Many databases include one dimensional arrays whose elements are records.
 Arrays are also used to implement other data structures such as strings , stacks queues , heaps,
and hash tables.
 Arrays can be used for sorting elements in ascending or descending order.

39 Dept. of CSE, CBIT,KOLAR

You might also like