This C++ program finds the largest and smallest element in a matrix using pointers. The row and column values of the matrix are read into the variables m and n. Then the program uses nested for loop to read the values to the 2D array a[][] and also the address of the first element of each row is stored in the pointer array p[]. The variables l and s is initially set with the value at a[0][0], these variables are used to store the largest and smallest element. Then the program uses another nested for loop to check in each row for the largest and smallest element and stores it in the variables l and s. Then the value of l and s is displayed to the output screen.
Program
#include<iostream.h> #include<conio.h> void main() { int a[10][10],*p[10],m,n,i,j,s,l; cout<<"Enter the order of matrics: "; cin>>m>>n; cout<<"Enter the elements\n\n"; for(i=0;i<m;i++) { p[i]=&a[i][0]; for(j=0;j<n;j++) { cin>>a[i][j]; } } l=a[0][0]; s=a[0][0]; for(i=0;i<m;i++) { for(j=0;j<n;j++) { if(*(p[i]+j)>l) l=*(p[i]+j); if(*(p[i]+j)<s) s=*(p[i]+j); } } cout<<"\nLargest element is: "; cout<<l; cout<<"\nSmallest element is: "; cout<<s; getch(); }
No comments:
Post a Comment