Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing leading spaces and zeros in C/C++

Tags:

c

printf

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 ?

like image 748
Sam Avatar asked Dec 01 '22 14:12

Sam


1 Answers

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);
like image 66
Ali Akber Avatar answered Dec 06 '22 19:12

Ali Akber