Example HTML page

C Program to print the maximum and minimum element in 2 Dimensional array.

In this section, we are writing a program for printing the maximum and minimum element in an array of order mXn.

For example, if the order of matrix is 2X2.

Then, to get the maximum element, we require one input matrix.

For example:

First matrix:

1 2

3 4

max:   4

To write this program, do the following things.

Step 1: read the elements in to the matrix

Step 2: write the logic for finding the maximum element in the matrix.

// to find the largest element, a[0][0] is assigned to max. then this element is compared with all the other elements present in the array using for loop.

The following program is for 3X3 matrix.

C Program for finding the maximum element:

#include<stdio.h>
int main()
{
    int a[3][3],i,j,max;
    max=a[0][0];
    // read the elements in to the array.
    printf("Enter the elements in to the matrix:\n");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&a[i][j]);
                    }
    }
         
    // logic for finding maximum element
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            if(a[i][j]>max)
            max=a[i][j];
        }
    }
     
     
    printf("\n%d",max);
}

Finding the maximum element in 2-D Matrix

Output:

Command Prompt

Enter the elements in to the matrix:
1 2 3
7 8 9
0 6 5
Max: 9

C Program for finding the minimum element:

If we change the “<” Symbol to “>” in the if condition inside the for loop in the logic we will get the minimum element. if you need you can change the variables max to min for readability.

#include<stdio.h>
int main()
{
    int a[3][3],i,j,min;
    min=a[0][0];
    // read the elements in to the array.
    printf("Enter the elements in to the matrix:\n");
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            scanf("%d",&a[i][j]);
                    }
    }
         
    // logic for finding maximum element
    for(i=0;i<3;i++)
    {
        for(j=0;j<3;j++)
        {
            if(a[i][j]<min)
            min=a[i][j];
        }
    }
     
     
    printf("Min: \n%d",min);
}

Finding the minimum element in 2-D Matrix

Output:

Command Prompt

Enter the elements in to the matrix:
1 2 3
7 8 9
0 6 5
Min: 0

Thank you for visiting our blog.

 

Example HTML page

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest