I'm trying to write an algorithm that prints a matrix of X's and O's, given the following params:
int numRows
int numCols
int charsPerCol
int charsPerRow
e.g. calling
printXOMatrix(int charsPerCol, int charsPerRow, int numCols, int numRows);
with the parameters
printXOMatrix(3,2,15,8);
will result in the following being printed to stdout:
XXXOOOXXXOOOXXX
XXXOOOXXXOOOXXX
OOOXXXOOOXXXOOO
OOOXXXOOOXXXOOO
XXXOOOXXXOOOXXX
XXXOOOXXXOOOXXX
OOOXXXOOOXXXOOO
OOOXXXOOOXXXOOO
Here's my code so far, it seems to print correctly if the number of columns / the number of chars per column is different, but fails for example in the case of:
printXOMatrix(2,2,8,8);
the following is printed to stdout:
XXOOXXOO
OOXXOOXX
OOXXOOXX
XXOOXXOO
XXOOXXOO
OOXXOOXX
OOXXOOXX
XXOOXXOO
How do I handle this edge case/clean up my code? Here's what I have so far:
#include <stdio.h>
void getXAndOGrid(int charsPerCol, int charsPerRow, int numCols, int numRows) {
char c = 'X';
for (int i=1; i<=(numCols*numRows); i++) {
// if current index is divisible by the columns (new row)
if (i % numCols == 0) {
// print character, then newline
printf("%c\n", c);
// if current index is divisible by number of columns times num of chars in column
if (i % (numCols * charsPerRow) == 0) {
if (c == 'O') {
c = 'X';
} else {
c = 'O';
}
}
// else if current index is divisible by num in row before it alternates
// and is not divisible by number of columns
} else if (i % charsPerCol == 0) {
printf("%c", c);
if (c == 'O') {
c = 'X';
} else {
c = 'O';
}
} else {
printf("%c", c);
}
}
}
int main() {
getXAndOGrid(3,2,15,8);
return 0;
}