By including extra codes between the % symbol introducing an output conversion specification and the conversion type letter it is possible to exercise considerable control over the appearance of the output produced by printf().
When an internal value is converted to external form by printf() the set of printing positions occupied by the external form is known as an output field . The number of characters in such a field is the width of the field. The simple %d conversion specification specifies an output field whose width is always just sufficient to accommodate the required number of digits and, if required, a negative sign.
By incorporating a number between the "%" symbol and the "d" you can specify the output field width. The output field width will never be less than the width you have specified, leading spaces will be generated by printf() as necessary. If the number to be converted is too big to fit in the output field then printf() will increase the size of the output field so leading digits are not lost.
The specification of output field widths is useful and important if you are attempting to print tidy columns of figures or print in particular positions on pre-printed stationery. It is important to consider the maximum values you are going to have to print out and define the output field width appropriately.
The following version of the sum of two numbers program shows the use of output field width specification.
>>
and
<<
are included in the layout specification so the output field limits are clearly visible in the output.
main()
{
int i,j;
printf("Enter numbers ");
scanf("%d%d",&i,&j);
printf("The sum was >>%3d<<\n",i+j);
}
Here's the output produced by the program known as
sum3 .
In the first run note the two leading spaces before the 7 and in the final run note that the output field width has expanded to 4. $ sum3 Enter numbers 3 4 The sum was >> 7<< $ sum3 Enter numbers 120 240 The sum was >>360<< $ sum3 Enter numbers 999 999 The sum was >>1998<<If the field width specification includes a leading zero then the leading spaces will become leading zeroes in the output. This may be useful for displaying times using the 24 hour clock or compass bearings. For example.
main()
{
int i,j;
printf("Enter numbers ");
scanf("%d%d",&i,&j);
printf("The sum was >>%06d<<\n",i+j);
}
A run of this program is shown. $ sum4 Enter numbers 123 512 The sum was >>000635<< $ sum4 Enter numbers 500000 1 The sum was >>500001<<There are various other options associated with d output conversion. For further information you should read the manual pages for the printf() function.