Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the power of 10 - Printf in C

Tags:

c

printf

printing

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
like image 907
RPAnimation Avatar asked Jan 27 '23 04:01

RPAnimation


2 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;
}
like image 154
dbush Avatar answered Feb 07 '23 13:02

dbush


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;
}
like image 25
Weather Vane Avatar answered Feb 07 '23 15:02

Weather Vane