0
need some help
the input is an odd number x and the output should be a rectangle consisting of c and d whit x rows and columns input = 5 output: cdcdc dcdcd cdcdc dcdcd cdcdc there is my try but it's not what i expected #include <stdio.h> void func(){ int x, i, j; char c[2] = "c", d[2] = "d"; printf("x = "); scanf("%d", &x); for (i = 1; i <= x; i++){ for (j = 1; j <= x; j++){ printf("%s%s", c, d); } printf("\n"); } } int main() { func(); return 0; }
5 odpowiedzi
+ 2
i iterate fom 0 to x-1,
j iterate from 0 to x-1
i*x + j will iterate from 0 to x*x-1
for example, if x = 5
the i*x + j will be
0 1 2 3 4 // for 1st row
5 6 7 8 9 // for 2nd row
10 11 12 13 14 // for 3rd row
15 16 17 18 19 // for 4th row
20 21 22 23 24 // for 5th row
% 2 means take remainder after division by 2
for even numbers it will be 0
for odd numbers it will be 1
that remainder then is added to character 'c'
'c' + 0 = 'c'
'c' + 1 = 'd'
printf("%c", value);
outputs value as character
+ 2
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
for(int i = 0; i < x; ++i){
for(int j = 0; j < x; ++j){
printf("%c", 'c' + (i*x + j) % 2);
}
printf("\n");
}
return 0;
}
0
can you explain?
0
i don't understand this line
printf("%c", 'c' + (i*x + j) % 2);
0
Thanks