# C Program to Find Largest Element in a Matrix

In this tutorial we will learn about how to create a program in C that will find and print the largest element from a matrix. This program will ask from user to enter any 3*3 matrix, and then find out the largest element from that given 3*3 matrix (by user at run-time)

```// Find Largest Element in a Matrix
// ----codescracker.com----

#include<stdio.h>
#include<conio.h>
int main()
{
int mat, i, j, max;
printf("Enter any 3*3 matrix: ");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
scanf("%d", &mat[i][j]);
}
max = mat;
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
if(max<mat[i][j])
max = mat[i][j];
}
}
printf("\nLargest Element = %d", max);
getch();
return 0;
}```

As the above program was build and run under Code::Blocks IDE, therefore here is the sample run after successful build and run:

Now enter all the 9 elements of 3*3 matrix and press `ENTER` key to see the largest one from all the 9 numbers:

#### Program Explained

• Receive 3*3 matrix as input. That is, any 9 numbers or elements as input from user at run-time
• Here we have used two for loop, the outer one is responsible for row and the inner one is responsible for column of the matrix
• That is, at first run of the outer for loop, the loop variable i holds its initial value as 0 and 0 is greater than 3, therefore the program flow goes inside the inner for loop, the loop variable say j gets initialized to 0 as its initial value, and as 0 is greater than 3, therefore program flow goes inside the inner for loop and a number gets scanned from user at run-time and initialized to mat[i][j] or mat
• Now the value of j gets incremented and becomes 1. As 1 is again greater than 3, therefore program flow again goes inside the inner for loop, and again another number gets scanned from user at run-time, and initialized to mat[i][j] or mat
• In similar way, all the 9 values gets stored one by one in this way:
• First value gets stored at mat
• Second at mat
• Third at mat
• Fourth at mat
• Fifth at mat
• Sixth at mat
• Seventh at mat
• Eight at mat
• Ninth at mat
• Now let's suppose that the first value or the value present at 0th row and 0th column of the matrix is the largest value. That is initialize mat to a variable say max (holds largest element of matrix)
• Now compare the value of max with each and every elements (9 elements) of the matrix, if any element is found as greater than the value of max, then initialize that element to the variable max and continue to check for the next element until all the element gets compared with value of max
• At last print the value of max which will be the largest element of given matrix