简体   繁体   中英

How do I print x amount of integers per line in C?

How to print the integers from 1 to 20 using a while loop and the counter variable x .

I need to print only five integers per line. [ Hint : Use the calculation x % 5 . When the value of this is 0 , print a newline character ( \n ), otherwise print a tab character ( \t )]

My main question is: How to print 5 integers per line?

This is the code i have tried

#include<stdio.h>

int main ( void )
{
    int x = 0;
    while ( x <= 20 ) 
    {
        printf("%d", x);
        ++x;
    }
}

Print the integers from 1 to 20 using a while loop and the counter variable x.

but your code print the integers from 0 to 20, replace int x = 0; by int x = 1;

Use the calculation x % 5 . When the value of this is 0, print a newline character, otherwise print a tab character.

in C that directly means

putchar((x%5) ? '\t' : '\n');

or doing in the printf

printf("%d%c", x, (x%5) ? '\t' : '\n');

so finally your code can be:

#include<stdio.h>

int main (void)
{
  int x = 1;
  
  while ( x <= 20 ) {
    printf("%d%c", x, (x%5) ? '\t' : '\n');
    ++x;
  }
}

Compilation and execution:

pi@raspberrypi:/tmp $ gcc -Wall c.c
pi@raspberrypi:/tmp $ ./a.out
1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
pi@raspberrypi:/tmp $ 

% is the modulo operation. a % b integer divide a by b and return the remainder. Thus 3 % 5 -> 3 and 7 % 5 -> 2.

You have the variable x which should go from 0 to 19. If you divide x by 5, the reminder will be a number in the range 0 to 4.

For x = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ..., x % 5 = 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1,...

As you can see, the remainder repeats the numbers from 0 to 4. These are 5 numbers.

So the trick is to print a new line only when x % 5 equals 4.

int x = 0;
while (x < 20) {
    printf("%d ", x+1);
    if (x % 5 == 4)
        printf("\n");
    x++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM