Four things: The first is to add spaces between the values. The second is to add newlines after each line. The third is to print the values as (unsigned) integers, and not as characters, neither of 255
nor 128
will print as valid characters. The fourth would be to use one loop for the height, with three loops inside it for the colors. Think of the loop counters as pixels instead, and you will understand why.
Why is my image not matching what I expect it to look like?
Pergunta
So, I have to create a ppm file that will give me the image of the italian flag (3 vertical bars in the order from left to right, green, white, and then red). And the image has to be 600 by 400. (columns by rows) I've tried rewriting my code multiple times, but, my image is just the three bars horizontally placed rather than vertically. Also, the lines aren't completely level. But the biggest issue is, why aren't my green, white, and red bars vertical? Any help is greatly appreciated.
Here's my code:
#include <stdio.h>
int main() {
printf("P6\n");
printf("%d %d\n", 600, 400);
printf("255\n");
int height, widthGreen, widthWhite, widthRed, i, j;
unsigned char Rcolor, Bcolor, Gcolor;
widthGreen = 200;
widthWhite = 400;
widthRed = 600;
height = 400;
for (j = 0; j < height; j++) {
for (i = 0; i < widthGreen; i++) {
Rcolor = 0;
Gcolor = 128;
Bcolor = 0;
printf("%c%c%c", Rcolor, Gcolor, Bcolor);
}
}
for (j = 0; j < height; j++) {
for (i = 201; i <= widthWhite; i++) {
Rcolor = 255;
Gcolor = 255;
Bcolor = 255;
printf("%c%c%c", Rcolor, Gcolor, Bcolor);
}
}
for (j = 0; j < height; j++) {
for (i = 401; i <= widthRed; i++) {
Rcolor = 255;
Gcolor = 0;
Bcolor = 0;
printf("%c%c%c", Rcolor, Gcolor, Bcolor);
}
}
return (0);
}
Solução
Outras dicas
Why are you using printf ? You should use the i and j index to build and index into an array. In your code, the i and j variable are only used as loop counter, not as coordinate.
What you are doing :
for each line
print some green
for each line
print some white
for each line
print some red
What you should be doing :
for each line
print some green
print some white
print some red
You could also use more meaningful variable name, like row instead of j and col (for column) instead of i