Print the power of 10 - Printf

3760 views c
4

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 0s 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

answered question

Are you allowed to use unsigned long long?

2 Answers

12

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;
}

posted this
13

Split 1 from other results:

#include <stdio.h>

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

posted this

Have an answer?

JD

Please login first before posting an answer.