Search code examples
cnested-loops

Repeating Characters (A B C) in C


Given numRows and numCols, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat, including after the last. Ex: numRows = 2 and numCols = 3 prints: 1A 1B 1C 2A 2B 2C

What I have:

#include <stdio.h>

int main(void) {
   int numRows = 2;
   int numCols = 3;

   int rows = 0;
   char cols = 'A';
   char var = 'A';

   for (rows = 1; rows<=numRows; ++rows){
      for (cols = 0; cols<numCols; cols++){
         printf("%d", rows);
         printf("%c ", var);

         ++var;

      }

   }

   printf("\n");

   return 0;
}

It prints:

1A 1B 1C 2D 2E 2F

But I would like it to print

1A 1B 1C 2A 2B 2C

How do I get it to repeat A B C?


Solution

  • Change your for loop to:

    for (rows = 1; rows<=numRows; ++rows){
      for (cols = 0; cols<numCols; cols++){
         printf("%d", rows);
         printf("%c ", var + cols % 3);
      }
    }
    

    You don't want to update the value of var since it refers to A.


    Here's a way better version:

    #include <stdio.h>
    
    int main(void) {
        int numRows = 2;
        int numCols = 5;
    
        for (int row = 1; row <= numRows; row++){
            for (int col = 0; col < numCols; col++){
                printf("%d%c ", row, 'A' + col);
            }
        }
        printf("\n");
        return 0;
    }