Newbie ICT IS
Newbie ICT IS

Reputation: 9

printing an equal number of character per line

i have a c printf program like this

for (r = 0; r <= 100 ; r++) {
        for (c = 0; c <= 100 ; c++) {

             printf("A");
        }
    }

how do i edit the code such that it would print 5 "A" per line such as

"AAAAA" but multiple line

Upvotes: 0

Views: 629

Answers (3)

chux
chux

Reputation: 154255

If the number of printed letters is a multiple of 5, print a '\n'

void NuBePrint(int rows, int cols, int period, char letter) {
  long count = 0;
  // OP may really want `r < rows` and `c < cols` to print 100x100 rather than 101x101
  for (int r = 0; r <= rows ; r++) {
    for (int c = 0; c <= cols; c++) {
      putchar(letter);
      count++;
      if (count%period == 0) putchar('\n');
    }
  }
  if (count%period != 0) putchar('\n');  // Cope with last line
}

// sample usage 
NuBePrint(100, 100, 5, 'A');

Upvotes: 0

C4d
C4d

Reputation: 3292

Check if the division c / 5 returns in a remainder of 0.

for (r = 0; r <= 20 ; r++) {
    for (c = 0; c <= 20 ; c++) {
        if (c%5 == 0) 
            printf("\r\n");
        printf("A");
    }
}

Upvotes: 2

George
George

Reputation: 2120

You just need to reduce the amount of columns to 5 and print a newline after each column cycle ends like this:

for (int row = 0; row < 20; ++row) {
    for (int column = 0; column < 5; ++column) {
         printf("A");
    }
    printf("\n");
}

Upvotes: 1

Related Questions