Reputation: 11
So I'm trying to read a 2D array from a file, find the smallest number in that array, and then subtract that number from each element in the array.
my file "ola4.dat" contains:
1 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2
I made the file so it'd be easy to spot that it was working because it should print a 0 and all 1's. For some reason my output is:
1 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
2 2 2 2 2
Can anyone please tell me where I'm am going wrong?
Thanks
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main ()
{
int numbers[5][10]; //array
int count 0;
ifstream myIn; //file name for ola4.dat
int lowest;
myIn.open("ola4.dat");
//loop to read in 2D array
for(int i = 0; i < 5; i++){
for(int j = 0; j < 10; j++){
myIn >> numbers[i][j];
}
}
lowest = numbers[0][0]; //setting lowest to first element in array
//loop to find lowest
for (int i = 0; i <5; i++){
for (int j = 0; j < 10; j++){
if(numbers[i][j] < lowest)
lowest = numbers[i][j];
}
}
//loop to subtract lowest from each element in the array
for (int i = 0; i <5; i++){
for (int j = 0; j < 10; j++){
numbers[i][j] - lowest;
}
}
//loop to print each element in the array
for (int i = 0; i <5; i++){
for (int j = 0; j <10; j++){
cout << numbers[i][j] <<' ';
}
cout << endl;
}
Upvotes: 1
Views: 389
Reputation: 1767
Try this below :
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main ()
{
int numbers[5][10]; //array
int count 0;
ifstream myIn; //file name for ola4.dat
int lowest;
myIn.open("ola4.dat");
//loop to read in 2D array
for(int i = 0; i < 5; i++){
for(int j = 0; j < 10; j++){
myIn >> numbers[i][j];
}
}
lowest = numbers[0][0]; //setting lowest to first element in array
//loop to find lowest
for (int i = 0; i <5; i++){
for (int j = 0; j < 10; j++){
if(numbers[i][j] < lowest)
lowest = numbers[i][j];
}
}
//loop to subtract lowest from each element in array
for (int i = 0; i <5; i++){
for (int j = 0; j < 10; j++){
numbers[i][j] -= lowest;
}
}
//loop to print each element in array
for (int i = 0; i <5; i++){
for (int j = 0; j <10; j++){
cout << numbers[i][j] <<' ';
}
cout << endl;
}
Upvotes: 0
Reputation: 206717
The line
numbers[i][j] - lowest;
doesn't do what you want to do. It just evaluates the term and discards it.
You need
numbers[i][j] -= lowest;
or
numbers[i][j] = numbers[i][j] - lowest;
I would suggest using the first form. It's simpler and less error prone.
It's not clear to me why you would get only 5 numbers per row in the output. You should get 10 numbers per row.
Upvotes: 1