In: Computer Science
(C++) Write a program that randomly fills in 0s and 1s into a 5-by-5 matrix,prints the matrix,and finds which row and column with more 1s and display that row and column number.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL));
int arr[5][5];
// randomly fills in 0s and 1s into a 5-by-5 matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
arr[i][j] = rand() % 2;
}
}
// prints the matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j) {
cout << arr[i][j] << " ";
}
cout << endl;
}
cout << endl;
// find row with more 1's
int maxRowIndex = 0, maxOnes = 0;
for (int i = 0; i < 5; ++i) {
int count = 0;
for (int j = 0; j < 5; ++j) {
if (arr[i][j] == 1)
++count;
}
if (count > maxOnes) {
maxOnes = count;
maxRowIndex = i;
}
}
cout << "row " << maxRowIndex+1 << " is maximum which contains " << maxOnes << " ones" << endl;
// find column with more 1's
int maxColumnIndex = 0;
maxOnes = 0;
for (int i = 0; i < 5; ++i) {
int count = 0;
for (int j = 0; j < 5; ++j) {
if (arr[j][i] == 1)
++count;
}
if (count > maxOnes) {
maxOnes = count;
maxColumnIndex = i;
}
}
cout << "column " << maxColumnIndex+1 << " is maximum which contains " << maxOnes << " ones" << endl;
return 0;
}
