Home > front end >  Explain the output of 2D array with nested loop code
Explain the output of 2D array with nested loop code

Time:03-05

#include <stdio.h>
int main()
{
    int i, j, k, px[] = { -2, -2, -1, -1, 1, 1, 2, 2 },
                 py[] = { -1, 1, -2, 2, -2, 2, -1, 1 };
    int cox[4][4] = { { 0 } };
    for (i = 0; i < 4; i  )
    {
        for (j = 0; j < 4; j  )
        {
            for (k = 0; k < 8; k  )
                if (((i   px[k]) >= 0 && (i   px[k]) < 4) &&
                    ((j   py[k]) >= 0 && (j   py[k]) < 4))
                    cox[i][j]  ;
            printf("%d\t", cox[i][j]);
        }
        printf("\n\n");
    }
}

I partially understand this nested loop. but i can't fully understand why its output in some part are 3 and why smiddle part are 4 but i understand why output of corner parts of this 2d array is 2.please explain me.

CodePudding user response:

As the result matrix is quadrant symmetric, let me start with examining the four cases: (i=0, j=0), (i=0, j=1), (j=1, i=0) and (i=1, j=1).

  • If (i=0, j=0), the condition (i px[k]) >= 0 && (i px[k]) < 4) && ((j py[k]) >= 0 && (j py[k]) < 4) meets twice: when k=5 and k=7.
  • If (i=0, j=1), the condition meets three times: when k=5, k=6 and k=7.
  • If (i=1, j=0), the condition meets three times: when k=3, k=5 and k=7.
  • If (i=1, j=1), the condition meets four times: when k=3, k=5, k=6 and k=7.

You can extend the similar consideration to the four quadrants then you can obtain the output.

  • Related