Tuesday 8 September 2015

Print leading 0's in C

How to print leading 0's in C ?

Sometimes it is required that we print leading 0's in a number for instance while printing time, 7:00 AM is actually printed as 07:00 AM and suppose a pin code like 011101 is to be printed.
This can be done by the following way:

printf("%0ad",var);

where a is the maximum no. of digits that your variable can be of, 
var is the variable itself.

Eg: 
1) To print 07:00, let us assume h=7, m=0
    
printf("%02d:%02d",h,m);

Output: 07:00

2) To print 011101, let var = 11101

printf("%06d",var);

Output: 011101

To see more such questions click the link below: More Questions

No comments:

Post a Comment