[prev] 34 [next]

Sidetrack: Printing Variable Values with printf()

Formatted output written to standard output (e.g. screen)

printf(format-string, expr1, expr2, …);

format-string can use the following placeholders:

%d  decimal       %f  floating-point
%c  character       %s  string
\n  new line       \"  quotation mark

Examples:

num = 3;
printf("The cube of %d is %d.\n", num, num*num*num);

The cube of 3 is 27.

id  = 'z';
num = 1234567;
printf("Your \"login ID\" will be in the form of %c%d.\n", id, num);

Your "login ID" will be in the form of z1234567.

  • Can also use width and precision:

    printf("%8.3f\n", 3.14159);
    

       3.142