29 April 2012

The "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 backslash (\) to indicate that the following character is a control character, rather that something to be printed.

printf("\tHello World\n");    will case 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 'answer' was 21.

Any number of place holders 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'

printf("If you add %d to %d you get %d", N1, N2, N1+N2);
Will display the message with 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 place. 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.

NOTE: If the data is too big for the space allocated for the space allocated in this way, the format specification will be over-ridden, and the full data will be displayed.

No comments:

Post a Comment