Duona Duona - 7 days ago 6
C++ Question

Calculations not working in Multidimensional array


I'm trying to do a program which would change all elements between first and the biggest numbers of each array collums into 0.
The programs works ,but i'm getting wrongs results.

This is input file:
3 5
2 3 5
1 2 4
4 1 3
6 1 2
5 8 1

This is the result file:
2 0 0 6 5
3 0 0 0 8
5 4 3 2 1

But i'm expecting the result like this:

2 3 5
0 0 4
0 0 3
6 0 2
5 8 1


I'm not sure if my code reads/prints information wrongly or i'm not understanding multidimensional array (i'm beginner in coding :) Any help would be appreciated, thanks.


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
int n, m, Z[100][100];

ifstream fr("input.txt");
ofstream fd("output.txt");

fr >> n >> m;

for(int i = 0; i < n ; i++)
for(int j = 0 ; j < m ; j++)
fr >> Z[i][j];

for(int i = 0; i < n ; i++)
{
int max = Z[0][0];
int NR = 0;

for(int j = 0 ; j < m ; j++)
{
if(Z[i][j] > max)
{
max = Z[i][j];
NR = j;
}
}

for(int j = 1 ; j < NR ; j++)
{
Z[i][j] = 0;
}
}

for(int i = 0; i < n ; i++)
{
fd<<endl;
for(int j = 0 ; j < m ; j++)
fd << Z[i][j]<<" ";
}


return 0;
}

Answer

Just swap m and n, refer below

fr >> m >> n;
Comments