Printing with indentation in C

Which way is the best for line up all the output on the right ?

Example: for powers of 2:

        2
        4
        8
       16
       32
       64
      128
      256
      512
     1024
     2048

     ...

134217728

If my last number has N digits, how print the first one (which in this case has just one digit) with (N - 1) spaces on left ?

Upvotes: 3

Views: 5726

Answers (3)

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26647

Example

int main(int argc, char *argv[]) {
    for (int i=2; i<134217729;i=i*2)
        printf("%*d\n",20, i);
    return 0;
}

Output

           2
           4
           8
          16
          32
          64
         128
         256
         512
        1024
        2048
        4096
        8192
       16384
       32768
       65536
      131072
      262144
      524288
     1048576
     2097152
     4194304
     8388608
    16777216
    33554432
    67108864
   134217728

Upvotes: 1

Barmar
Barmar

Reputation: 781058

You can supply a computed field width to printf() using *. So after you calculate the maximum number of digits, you can do:

printf("%*d\n", max_digits, value);

Upvotes: 5

shole
shole

Reputation: 4094

You can use the width trick of printf as said here: Printf reference

printf ("Width trick: %*d \n", 5, 10);

will produce

Width trick: 10

Upvotes: 2

Related Questions