Print the power of 10 - Printf in C

Viewed 727

I have to print the powers of 10 ranging from 0-19. The problem is when I want to display the first power, which should be 1 (10^0), I just can't force printf to not repeat the 0's whatsoever. I am allowed to only use one printf in my program and one { } block (which is main function).

#include <stdio.h>

int main(void) {
    int power = 19;
    for (int i = 0; i <= power; i++)
        printf("1%0*d\n",i, 0);
    return 0;
}

My output:

10 // this should be 1, but printf still puts 0 here
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000000
100000000000
1000000000000
10000000000000
100000000000000
1000000000000000
10000000000000000
100000000000000000
1000000000000000000
10000000000000000000
3 Answers

Instead of using %d, use %s with a variable precision, and have it print from a string of zeros. If the precision is 0, no characters are printed.

#include <stdio.h>

int main(void) {
    int power = 19;
    char zeros[] = "00000000000000000000";
    for (int i = 0; i <= power; i++)
        printf("1%.*s\n",i, zeros);
    return 0;
}

As commented by @Weather Vane, use unsigned long long with can handle values up to at least 18,446,744,073,709,551,615 or 264 - 1.

int main(void) {
  unsigned long long power = 0;
  for (int i = 0; i <= 19; i++)
    printf("%d %llu\n", i, power = power ? power*10 : 1);
  return 0;
}

Output

0 1
1 10
2 100
...
17 100000000000000000
18 1000000000000000000
19 10000000000000000000

Or if one does not like to hard code initialization stings like "00000000000000000000", assign the elements in the same loop.

Note "%.*s" can print a non- null character terminated char array.

#define MAX10POWER 30

int main(void) {
  char zeros[MAX10POWER];
  for (int i = 0; i <= MAX10POWER; zeros[i++] = '0')
    printf("%d 1%.*s\n", i, i, zeros);
  return 0;
}

Output

0 1
1 10
2 100
...
28 10000000000000000000000000000
29 100000000000000000000000000000
30 1000000000000000000000000000000

Or a sneaky variation of Weather Vane good answer to go up to 21.

int main(void) {
  for (unsigned long long power = 1, i = 0; i <= 21; i++, power *= 8)
    printf("%lld %llo\n", i, power);
}

You can achieve the desired result like this:

#include <stdio.h>

int main(void) {
    unsigned long long power = 1;
    for (int i = 0; i <= 19; i++, power *= 10)
        printf("%llu\n", power);
    return 0;
}
Related