- Programming in C
- Notes on printf
- printf is used to display data on the screen. Its simplest form is:
printf("Hello World");
This statement tells the program to display the data in the inverted commas (known as the format string) on the screen.
You can control movement around the screen to some extent by the use of escape characters. Use a backlash (\) to indicate that the following character is a control character, rather than something to be printed.
printf("\tHello World\n");
The above code will cause a tab space before the words and a new line after. Any number of escape characters can be included in a format string.
If you wish to print data from variables, you must insert place holders in the format string to show where you want the data inserted, and an argument list after the format string to indicate which variables to display. Place holders are indicated by the percent sign (%).
For example:
printf("The answer is %d",answer);
Will display 'The answer is 21', assuming that the value of the variable to 'answer' was 21.
Any number of place holder can be included.
printf("If you add %d to %d you get %d",21,32,57);
Will display 'If you add 21 to 32 you get 57'
or:
printf("If you add %d to %d you get %d",N1,N2,N1+N2);
Will display the message the values of the variables.
Place holders show not only the place where a variable is to be inserted, but also the type of variable to be inserted. This is indicated by the character that follows the %.
d = integer, f = float, c = character, s = string
NOTE: You must exactly match the place holders to the argument list; for instance:
int age=21;
float salary=595.75;
char initial='F';
char name[20]="Bloggs";
printf("%c, %s, is %d years old and earns $%f\n",initial,name,age,salary);
Will display 'F.Bloggs is 21 years old and earns $595.750000' and then go to a new line.
Note that the float printed with six decimal places. The space taken up by a printed field can be controlled by using formatting within the place holder:
printf("The float is %8.2f,num");
Will allow 8 spaces for the data to be displayed, and will round to 2 decimal places.
printf("%-15s is my name",name);
Will allow 15 spaces for the name, and the minus sign will provide left justification.
NOTES:
- If the data is too big for the space allocated in this way, the format specification will be over-ridden, and the full data will be displayed.