Go through 4x4 matrix with for, I don’t understand

Asked

Viewed 395 times

0

I don’t understand that code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i, j;
    for(i=1; i<5; i++) {
        for(j=1; j<5; j++) {
            if(i==j)
                printf("1 ");
            else
                printf("0 ");
        }
        printf("\n");
    }
    system("pause");
    return 0;
}

It assigns value 1 if true and 0 for false, but if the two are equal, I do not understand, because only a vertical line 1. and not all 1.

1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1

1 answer

3


  • In the 1st iteration of first for the value of the variable i is 1.

  • As soon as you enter this for enters in a second for (that is within the first) the value of its variable j is also 1 logo will be printed 1.

  • In the next iterations the value of j of the second for will not match the first for for the value of i has not yet been amended as an iteration of the first for.

  • As soon as the 1st iteration on first for the value of i will be increased to 2 and the value only matched that of j when the 2nd is in the second iteration, printing 1. And so on and so forth.

  • Then the values of the counting variables of each for will only be equal when both are in the same iteration (when both for external and intern are in the 1st, 2nd, 3rd and 4th iteration)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.