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
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;
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With