Printing Leading Spaces and Zeros in C

I need to print some leading spaces and zeros before the number, so the output will be like this:

00015
   22
00111
    8
  126

here i need to print leading spaceswhen the number evenand leading zerowhenodd

Here is 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 a way for quick access?

+4
source share
1 answer

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);
+14
source

All Articles