-7

So, i have three numbers that can be < 100;

How can i printf those numbers to look like this:

{10, 5,20}
{ 1, 6, 2}
{19,18, 7}

instead of this

{10,5,20}
{1,6,2}
{19,18,7}

and it is possible to use only printf(no ifs)?

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122
Keyzi
  • 7
  • 2

2 Answers2

0

printf("%2d", yournumber) will print number with 2 characters. If number is less than 2 chars long, spaces will be included before number.

In case number is bigger than 2 digits, modifier has no effect and entire number will be printed.

printf("%2d", 1);   //  " 1"
printf("%2d", 10);  //  "10"
printf("%2d", 100); // "100"
unalignedmemoryaccess
  • 7,246
  • 2
  • 25
  • 40
0

You have to specify the width of the field using "%2d", you can change 2 for the width that you like.

#include <stdio.h>

int main() {
    printf("%2d,%2d,%2d\n", 10,5,20);
    return 0;
}