Reputation: 39
I am learning basic programming in C and I have problems with a file writing exercise. The problem is to write a square matrix in a file but in the following way: The first two numbers in each row should be separated by "," and then write the remaining numbers separately.
It is a fairly simple exercise but I am just learning, I leave my code that has some flaws. I hope you can help me.
#include <stdio.h>
int main(){
FILE *data;
int matrix[4][4] = {
{1,2,3,4},
{2,3,5,6},
{9,8,4,5},
{5,3,1,2}
};
data = fopen("output.txt","w");
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
if(matrix[i][0]>=0&&matrix[i][j+1]<4)
{
fprintf(data, "%d,%d ",matrix[i][j],matrix[i][j+1]);
}
else
fprintf(data, "%d ",matrix[i][j]);
}
fprintf(data, "\n");
}
fclose(data);
return = 0;
}
I Know that my big mistake is the condition of the if sentence but I don't know how to write that correctly for this case.
I want to obtain this output:
1,2 3 4
2,3 5 6
9,8 4 5
5,3 1 2
How can I fix the if sentence or do something different to obtain that output?
Upvotes: 2
Views: 109
Reputation: 589
You were close but your logic was a little off, try printing them one at a time and then checking for the index of the inner for loop to be the 0 index and then append the comma on the end.
Also on you return statement you are providing the value to return hence: return 0; you cannot assign return a value
Hope that helps, I did mine using printf and then changed it back to fprintf so there could be an error with that you may have to fix
#include <stdio.h>
int main(){
FILE *data;
int matrix[4][4] = {
{1,2,3,4},
{2,3,5,6},
{9,8,4,5},
{5,3,1,2}
};
data = fopen("output.txt","w");
for (int i = 0; i < 4; ++i)
{
fprintf(data, "%d,", matrix[i][0]);
for (int j = 1; j < 4; ++j)
{
fprintf(data, "%d ", matrix[i][j]);
}
fprintf(data, "\n");
}
return 0;
}
Upvotes: 1
Reputation: 15320
There are two ways to get what you want.
The most obvious way, is just to emit all 4 values at the same time:
for (int i = 0; i < 4; ++i) {
int i0 = matrix[i][0];
int i1 = matrix[i][1];
int i2 = matrix[i][2];
int i3 = matrix[i][3];
fprintf(data, "%d,%d %d %d\n", i0, i1, i2, i3);
}
The other way is to use conditionals based on the value of j
, not on matrix[i][j]
. There are three possible things you might print before/after a value:
So you can check to see what j
value you are at, and print an appropriate string (not character, because "nothing" is not a character, but ""
is a nothing string).
for (int i ...
for (int j = 0; j < 4; ++j) {
const char * before = "";
if (j == 1) before = ",";
if (j > 1) before = " ";
fprintf(data, "%s%d", before, matrix[i][j]);
}
fprintf(data, "\n");
}
As you get more confident, you can initialize the before
string with a ternary expression.
You could also use an "after" string instead, which would eliminate the extra fprintf(data, "\n")
after the loop.
Upvotes: 1