C++ Program to Find Largest and Second Largest Number in 2D Array

Here is the C++ program to find largest and second largest number in a 2d array or matrix.

#include<iostream>

using namespace std;

int main()
{
    int a[5][5],big1=1,big2=0,n,m,i,j;
    cout<<"Enter no of rows and columns(max 5):";
    cin>>m>>n;
    cout<<"Enter the array:\n";

    for(i=0;i<m;i++)
        for(j=0;j<n;++j)
            cin>>a[i][j];

    for(i=0;i<m;++i)
        for(j=0;j<n;++j)
        {
            if(a[i][j]>big1)
                big1=a[i][j];
        }

    for(i=0;i<m;++i)
        for(j=0;j<n;++j)
        {
            if(a[i][j]>big2&&a[i][j]<big1)
                big2=a[i][j];
        }

    cout<<"\nLargest number:"<<big1;
    cout<<"\nSecond largest number:"<<big2;

    return 0;
}

Output

Enter no of rows and columns(max 5):3
3
Enter the array:
4 6 8
2 4 6
2 12 5
Largest number:12
Second largest number:8

5 thoughts on “C++ Program to Find Largest and Second Largest Number in 2D Array”

  1. i would like to see thhis solution

    find the maximum element in even rows of a matrix using C++ programming.

    thank you

Leave a Comment

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