Reputation: 59
I created an array of A[rows][columns] random numbers between 100 and -100 saved it in txt file Now i have to check if all numbers are negative in column and if so save column number in array C[x];
int main()
{
ofstream out("masyvas.txt");
srand(time(0));
int n=rand() % (31 - 10) + 10; // eilutes
int m=rand() % (31 - 10) + 10; // stulepliai
int A[n][m];
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
A[i][j]=rand()%100 + (rand()%100 *(-1)) ;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
out<<setw(5)<<A[i][j]<<" ";
out<<endl;
}
out.close();
//------------------------------------------
return 0;
}
so above everything is ok but
ofstream rez("rez.txt");
for(int i=0; i < m;i++)
{
for(int j=0; j< n;j++) {
if(A[i][j]<0){
rez << i <<" - column" << j << "- row"<< endl;
}
}
}
cout << n << endl << m << endl;
rez.close();
first i wanted to print into txt file if it finds negative numbers correctly but i get some nonsense and i have no clue what to do im stuck for half an hour trying to do different things
Upvotes: 0
Views: 684
Reputation: 69
First thing, don't panic, read your code and actually know what it is doing.
To check if all numbers in a column are negative, you need to loop over an entire column first while having something, preferably a boolean, to tell you if any of them is not negative.
For example: create a flag that defaults to true.
bool allNegative = true;
for ( int i =0; i < (sizeof(matrix[0])/sizeof(int)); i++)
{
if(matrix[i][0] > 0) allNegative = false; // change the flag to indicate that it is not all negative
}
Then what you want to do is if the flag is still true, loop that column again to just copy and paste all this code for each row to output that column to a txt file.
out<<setw(5)<<A[i][j]<<" ";
out<<endl;
EDIT: thanks to comment, I have changed the syntax error.
Upvotes: 2