I need to print some leading spaces and zeros before a number, so that the output will be like this:
00015
22
00111
8
126
here, I need to print leading spaces
when the number is even
and leading zero
when odd
Here's how I did it :
int i, digit, width=5, x=15;
if(x%2==0) // number even
{
digit=log10(x)+1; // number of digit in the number
for(i=digit ; i<width ; i++)
printf(" ");
printf("%d\n",x);
}
else // number odd
{
digit=log10(x)+1; // number of digit in the number
for(i=digit ; i<width ; i++)
printf("0");
printf("%d\n",x);
}
Is there any shortcut way to do this ?
To print leading space and zero
you can use this :
int x = 119, width = 5;
// Leading Space
printf("%*d\n",width,x);
// Leading Zero
printf("%0*d\n",width,x);
So in your program just change this :
int i, digit, width=5, x=15;
if(x%2==0) // number even
printf("%*d\n",width,x);
else // number odd
printf("%0*d\n",width,x);
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