Home > Software engineering >  How to run an If statement >between< other If statements in clean way
How to run an If statement >between< other If statements in clean way

Time:11-29

This is the If statment I want to be able to run between all other If statements. It controls if the index of a two dimensional array has the value of 9. IF it does then it should be reset to a value of 0.

if (numbers[row, col] == 9)
{
     numbers[row, col] = 0;
}

Basically, no value should ever get above 9 in value.

The code below is where I want to use the above if statement to control this.

// These are the "other" IF statements.
    if (row < 9 && col <= 9)
    {
        numbers[row   1, col]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row > 0 && col <= 9)
    {
        numbers[row - 1, col]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row >= 0 && col < 9)
    {
        numbers[row, col   1]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row >= 0 && col > 0)
    {
        numbers[row, col - 1]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row < 9 && col > 0)
    {
        numbers[row   1, col - 1]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row < 9 && col < 9)
    {
        numbers[row   1, col   1]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row > 0 && col > 0)
    {
        numbers[row - 1, col - 1]  = 1;
    }
    //RUN IF STATEMENT HERE
    if (row > 0 && col < 9)
    {
        numbers[row - 1, col   1]  = 1;
    }
    //RUN IF STATEMENT HERE

CodePudding user response:

As your array is has two dimensions, use a two-level, nested loop, like this:

for (int i = 0; i < numbers.GetLength(0); i  )
    for (int j = 0; j < numbers.GetLength(1); j  )
        if (numbers[i, j] >= 9)
            numbers[i, j] = 0;
  • Related