Home > front end >  How do I avoid checking everything with a different If using for loops?
How do I avoid checking everything with a different If using for loops?

Time:11-14

In C , how do I avoid walls of ifs using for loops? stackoverflow is requesting more text soo... Code Example:

if(masiv[0][0] == 'X'){
    masiv[0][0] = '1';
}
if(masiv[0][1] == 'X'){
    masiv[0][1] = '2';
}
if(masiv[0][2] == 'X'){
    masiv[0][2] = '3';
}
if(masiv[1][0] == 'X'){
    masiv[1][0] = '4';
}
if(masiv[1][1] == 'X'){
    masiv[1][1] = '5';
}
if(masiv[1][2] == 'X'){
    masiv[1][2] = '6';
}
if(masiv[2][0] == 'X'){
    masiv[2][0] = '7';
}
if(masiv[2][1] == 'X'){
    masiv[2][1] = '8';
}
if(masiv[2][2] == 'X'){
    masiv[2][2] = '9';
}

CodePudding user response:

for (int y = 0; y < 3;   y) {
  for (int x = 0; x < 3;   x) {
    if (masiv[y][x] == 'X') {
      masiv[y][x] = '1'   3 * y   x;
    }
  }
}

Some explanation follows.

The following pattern is repeating:

if (masiv[...][...] == 'X') {
  masiv[...][...] = '...';
}

Because it is repeating, we put it to the body of the for loop.

We need 2 for loops, because the first and the second indexes in masiv[...][...] go over all possible values independently, and each variation is present. We will use a separate loop variable for each index, thus it becomes masiv[y][x].

The lower limit for y is 0 (inclusive) and the upper limit for y is 3 (exclusive), hence the for line looks like: for (int y = 0; y < 3; y) {. Similarly for x.

We need a different character after the masiv[y][x] =. Since digits are next to each other in the ASCII table (e.g. '5' 3 == '8'). we use an expression like '1' ...y... ...x.... The actual value starts from '1' in the beginning, and it increases by 1 as x increases, and it increases by 3 when y increases. Thus it's '1' 3 * y x.

  •  Tags:  
  • c
  • Related