I am trying to create a program in C to draw this pattern :
1 1 2 1 3 1
1 2 2 2 3 2
1 3 2 3 3 3
1 4 2 4 3 4
1 5 2 5 3 5
I checked the answer from solutions.
#include <stdio.h>
int main ()
{
int i;
int j;
for (i = 1 ; i <= 5 ; i++)
{
for (j = 1 ; j <= 3 ; j++)
{
printf("%i %i",j,i);
}
printf("\n");
}
return 0;
but I can't understand why this code (Above) gives the previous result instead of this result :
1 2 3 1
1 2 3 2
1 2 3 3
1 2 3 4
1 2 3 5
1 2 3 1
1 2 3 2
1 2 3 3
1 2 3 4
1 2 3 5
This output would appear if each iteration of the inner loop printed the value of j
(1, 2, 3), and then, just after the inner loop, the value of i
were printed. However, that is not what the code says. The inner loop contains printf("%i %i",j,i);
, and that prints two numbers each time it is called, one for j
and one for i
.
To print the value for i
separately after all the values for j
, you would need a separate printf
, as in:
for (i = 1 ; i <= 5 ; i++)
{
for (j = 1 ; j <= 3 ; j++)
{
printf("%i ", j);
}
printf("%i\n", i);
}