Wednesday, November 2, 2011

Format Specifications in C programming language

The %d and %f used in the printf( ) are called format specifiers. They tell printf( ) to print the value of avg as a decimal integer and the value of per as a float. Following is the list of format specifiers that can be used with the printf( ) function.


We can provide following optional specifiers in the format specifications.


Now a short explanation about these optional format specifiers. The field-width specifier tells printf( ) how many columns on screen should be used while printing a value. For example, %10d says, “print the variable as a decimal integer in a field of 10 columns”. If the value to be printed happens not to fill up the entire field, the value is right justified and is padded with blanks on the left. If we include the minus sign in format specifier (as in %-10d), this means left justification is desired and the value will be padded with blanks on the right. Here is an example that should make this point clear.
 
main( )
{
int weight = 63 ;
printf ( "\nweight is %d kg", weight ) ;
printf ( "\nweight is %2d kg", weight ) ;
printf ( "\nweight is %4d kg", weight ) ;
printf ( "\nweight is %6d kg", weight ) ;
printf ( "\nweight is %-6d kg", weight ) ;
}

The output of the program would look like this ...
Columns 0123456789012345678901234567890
weight is 63 kg
weight is 63 kg
weight is 63 kg
weight is 63 kg
weight is 63 kg

Specifying the field width can be useful in creating tables of numeric values, as the following program demonstrates.
 
main( )
{
printf ( "\n%f %f %f", 5.0, 13.5, 133.9 ) ;
printf ( "\n%f %f %f", 305.0, 1200.9, 3005.3 ) ;
}
And here is the output...
5.000000 13.500000 133.900000
305.000000 1200.900000 3005.300000
Even though the numbers have been printed, the numbers have not been lined up properly and hence are hard to read. A better way would be something like this...
 
main( )
{
printf ( "\n%10.1f %10.1f %10.1f", 5.0, 13.5, 133.9 ) ;
printf ( "\n%10.1f %10.1f %10.1f", 305.0, 1200.9, 3005.3 );
}

This results into a much better output...
01234567890123456789012345678901
5.0 13.5 133.9
305.0 1200.9 3005.3
The format specifiers could be used even while displaying a string of characters. The following program would clarify this point:
 
/* Formatting strings with printf( ) */
main( )
{
char firstname1[ ] = "Sandy" ;
char surname1[ ] = "Malya" ;
char firstname2[ ] = "AjayKumar" ;
char surname2[ ] = "Gurubaxani" ;
printf ( "\n%20s%20s", firstname1, surname1 ) ;
printf ( "\n%20s%20s", firstname2, surname2 ) ;
}

And here’s the output...
012345678901234567890123456789012345678901234567890
Sandy Malya
AjayKumar Gurubaxani

The format specifier %20s reserves 20 columns for printing a string and then prints the string in these 20 columns with right justification. This helps lining up names of different lengths properly. Obviously, the format %-20s would have left justified the string.

No comments:

Post a Comment