Search code examples
arrayscfor-loop

is there a way to resolve this problem without using many "if loops"?


The variables i and j are integers, and the variable a memorizes a two-dimensional array with 5 lines and 5 columns, numbered from 1 to 5, initially having all the elements null. Without using variables other than those mentioned, write the sequence of instructions below, replacing the ellipses so that, following the execution of the sequence obtained, variable A to memorize the adjacent table.

 for(i=1; i<=5; i++) 
  for(j=1; j<=5; j++)
............
<4 4 4 4 4 
4 3 3 3 3 
4 3 2 2 2 
4 3 2 1 1 
4 3 2 1 0

i tried this algorithm but it doesn't work

 for(i = 1; i <= 5; i++) 
    for(j = 1; j <= 5; j++) {
        int max_value;
        if ((i - 1) > (j - 1))
            max_value = i - 1;
        else
            max_value = j - 1;
        a[i][j] = 4 - max_value;

Solution

  • In c array indices start at 0 not 1. If your input array is int a[5][5] then you are off-by one in both dimensions which is undefined behavior.

    You can use the conditional operator ?: like @nabinsademba showed you as an alternative to the if-statement. It's still a conditional assignment so the only effect is that it looks a little more compact:

    #include <stdio.h>
    
    int main() {
        int a[5][5] = { 0 };
        for(int i = 0; i < sizeof a / sizeof a[0]; i++)
            for(int j = 0; j < sizeof a[0] / sizeof a[0][0]; j++) {
                a[i][j] = 4 - (i > j ? i : j);
                printf("%d%s", a[i][j], j < sizeof a[0] / sizeof a[0][0] - 1 ? ", " : "\n");
            }
    }
    

    and here is the example output:

    4, 3, 2, 1, 0
    3, 3, 2, 1, 0
    2, 2, 2, 1, 0
    1, 1, 1, 1, 0
    0, 0, 0, 0, 0
    

    If you want the output you showed then it's a slightly different assignment:

    #include <stdio.h>
    
    int main() {
        int a[5][5] = { 0 };
        for(int i = 0; i < sizeof a / sizeof a[0]; i++)
            for(int j = 0; j < sizeof a[0] / sizeof a[0][0]; j++) {
                a[i][j] = 4 - (i < j ? i : j);
                printf("%d%s", a[i][j], j < sizeof a[0] / sizeof a[0][0] - 1 ? ", " : "\n");
            }
    }
    

    and:

    4, 4, 4, 4, 4
    4, 3, 3, 3, 3
    4, 3, 2, 2, 2
    4, 3, 2, 1, 1
    4, 3, 2, 1, 0