John Smith John Smith - 2 months ago 240
C Question

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 it's supposed to print 1A 1B 1C 2A 2B 2C

How do I get it to repeat A B C?

Answer

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