Input numbers in 2d array and print the largest and smallest number in C++
Two Dimensional Array - Question 3
In this question, we will see how to input numbers in a 3X3 integer matrix (2d array) and print the largest and smallest number from it in C++ programming. To know more about two dimensional array click on the two dimensional array lesson.
Q3) Write a program in C++ to input numbers in a 3X3 integer matrix (2d array) and print the largest and smallest number from it.
Program
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int a[3][3], r,c,lg=0,sm=0;
cout<<"Enter 9 numbers\n";
for(r=0; r<3; r++)
{
for(c=0; c<3; c++)
{
cin>>a[r][c];
if(r==0 && c==0)
{
lg=a[r][c];
sm=a[r][c];
}
else if(a[r][c]>lg)
{
lg=a[r][c];
}
else if(a[r][c]<sm)
{
sm=a[r][c];
}
}
}
cout<<"Largest number = "<<lg<<endl;
cout<<"Smallest number = "<<sm;
return 0;
}
Output
Enter 9 numbers 63 24 15 3 75 2 19 31 42 Largest number = 75 Smallest number = 2