Hello! I am a beginner in C++, and I'm pretty sure that my problem is really easy to solve, but I don't know how.. I have to create a 2d array with random numbers, print out max number of every row and then put all these max numbers in ascending order.. All I did - I made that 2d array, but I don't know how to continue.. I understand the idea of the task but don't know how to write the code.. Any help will be appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <cstdlib>
#include <ctime>
usingnamespace std;
int main(){
srand(time(0));
int N,M,i,j,max;
cout<<"Number of rows: "; cin>>N;
cout<<"Number of columns: "; cin>>M;
int a[N][M];
for(i=0; i<N; i++){
for(j=0; j<M; j++){
a[i][j]=rand()%100;
cout<<a[i][j]<<" ";
} cout<<"\n";
}
}
For what it's worth, line 10 is non-standard C++, although some compilers will allow it. In standard C++, the size of an array must be known at compile time.
Okay, to solve the problem, start by writing out the algorithm in english:
1 2 3 4 5
for each row {
compute the max value
}
sort the max values
output the sorted values.
Sorting the max values means that you'll have to store them somewhere. So you will need another array. This will be a one-dimensional array. Now the algorithm becomes
1 2 3 4 5 6
create maxValues array
for each row {
compute the max value for the row and store it in maxValues array
}
sort the max values array
output the max values array.
After I'll do that, how to put these max values in it?
The same as with any other array. You will have an array of max values. How big is this array? Since it holds one value of each row in the 2D array, it's the same size as the ROWS: int maxValues[N];
When you are done computing the max value for row i, just store it in maxValues[i].
BTW you have a bug. Suppose you compute that the max value for row 1 is 17. If the actual max value for row 2 is 8, then you will incorrectly print that it is 17. That's because the "max" variable still contains the old value from row 1. So you need to initialize it right before line 20.