There are two ways to output your number with leading zeroes:
Using the 0
flag and the width specifier:
int zipcode = 123;
printf("%05d\n", zipcode); // Outputs 00123
Using the precision specifier:
int zipcode = 123;
printf("%.5d\n", zipcode); // Outputs 00123
The difference between these is the handling of negative numbers:
printf("%05d\n", -123); // Outputs -0123 (pad to 5 characters)
printf("%.5d\n", -123); // Outputs -00123 (pad to 5 digits)
ZIP Codes are unlikely to be negative, so it should not matter.
Note however that ZIP Codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.
Note that in both examples above, the 5
width or precision values can be specified as an int
argument:
int width = 5;
printf("%0*d\n", width, 123); // Outputs 00123
printf("%.*d\n", width, 123); // Outputs 00123
There is one more trick to know: a precision of 0
causes no output for the value 0
:
printf("|%0d|%0d|\n", 0, 1); // Outputs |0|1|
printf("|%.0d|%.0d|\n", 0, 1); // Outputs ||1|