Search code examples
cfunctionfor-loopnested-loops

nested for loops ending sooner than expected


My code:

#include <stdio.h>
#include <math.h>

void block(int r, char a, char b);

int main(){
  block(2, '+', '-');
}

void block(int r, char a, char b){
  int i;
  char x = a;
  char y = b;
  for (i = 1; i <= r; i++){
    if ( i%2 == 1){
      for (i = 1; i <= r; i++){
        printf("%c", x);
      }
      for (i = 1; i <= r; i++){
        printf("%c", y);
      }
    } else
    {
      for (i = 1; i <= r; i++){
        printf("%c", x);
      }
      for (i = 1; i <= r; i++){
        printf("%c", y);
      }
    }
    printf("\n");
  }
  return;
}

intended output:

++--
--++

what I get instead:

++--

Nothing prints after the first line. For instance for r = 5 it prints the first line +++++----- correctly but doesn't print the remaining lines of the solution.

correct solution:

+++++-----
-----+++++
+++++-----
-----+++++
+++++-----

Solution

  • Thanks to @rustyx

    This ended up doing the trick for me.

    #include <stdio.h>
    #include <math.h>
    
    void block(int r, char a, char b);
    
    int main(){
      block(5, '+', '-');
    }
    
    void block(int r, char a, char b){
      int i;
      char x = a;
      char y = b;
      for (i = 1; i <= r; i++){
        if ( i%2 == 1){
          int j;
          for (j = 1; j <= r; j++){
            printf("%c", x);
          }
          for (j = 1; j <= r; j++){
            printf("%c", y);
          }
        }
        else{
          int k;
          for (k = 1; k <= r; k++){
            printf("%c", y);
          }
          for (k = 1; k <= r; k++){
            printf("%c", x);
          }
        }
        printf("\n");
      }
      return;
    }
    

    giving this result:

    +++++-----
    -----+++++
    +++++-----
    -----+++++
    +++++-----