Please correct my code

I always get 5 7 7 but should get the maximum numbers from each column. Please correct my code.

#include<ctime>
#include<iostream>
#include <cstdlib>
using namespace std;
int main()
{
const int ROWS{ 3 };
const int COLS{ 3 };
int col = 0, row = 0;
int matrix2[ROWS][COLS];

cout << "matrix2-" << ROWS << "x" << COLS << "\n\n";

for (int row{ }; row < ROWS; row++)
{
for (int col{ }; col < COLS; col++)
{
matrix2[row][col] = rand() % 10;
cout << matrix2[row][col] << ' ';;
}
cout << '\n';
}
cout << '\n';

int max = matrix2[row][col];
for (size_t row{ }; row<=2;row++)
{

for (auto& itr: matrix2[row])
{
if (itr > max) { max = itr; }

}
cout << max << endl;
}
With out code tags I am not going to bother with it this late.


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


You need to seed your random number generator with an initial call to srand().

You have multiple variables called row and col. Which is asking for trouble.

You are quite a long way from finding the maximum in each column: for that the column loop would need to be the outer loop and you would need to reset 'max' at the start of each new column. Also, calling a variable 'max' runs the risk of clashing with the standard library function of the same name.

Oh, and use code tags!
1
2
3
4
5
6
7
8
9
10
11
12
#include<ctime>
#include<iostream>
#include <cstdlib>
using namespace std;
int main(){const int R{3};
    const int C{3};
    int t[R][C],m{0};
    for(int y{0};y<R;y++){for(int x{0};x<C;x++){t[y][x]=rand()%10;
            cout<<t[y][x]<<' ';}cout<<'\n';}cout<<'\n';
    for(int y=0;y<R;y++){m=0;for (auto& i:t){m<*(i+y)?m=*(i+y):true;}cout<<m<<'\n';}
    return 0;
}

7 9 3 
8 0 2 
4 8 3 

8
9
3
Program ended with exit code: 0
Last edited on
Topic archived. No new replies allowed.