Sam
Sam

Reputation: 61

Printing leading spaces and zeros in C/C++

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 ?

Upvotes: 5

Views: 14894

Answers (1)

Ali Akber
Ali Akber

Reputation: 3800

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

Upvotes: 20

Related Questions