printf

The printf function is the main method used for outputting text in C programs. printf is a library function contained in the stdio library. The general form of printf is shown below.

	printf ( <format string>, arg1, arg2, arg3, ... ) ;

The format string can contain text, control characters and also markers that indicate where the value of a variable should be displayed within the output text. Following the format string are a list of variables (or constants) that should be output as part of the message. These variables are separated with commas. For each variable marker in the format string, there should be a corresponding variable included in the argument list. The following examples will show how printf is used.

Display text:


	printf("Hello World!");

Display text and move to the next line:

	printf("Hello World!\n");

The character sequence \n indicates that you should move to the next line. If this is not included, the next printf will print on the same line as this one. The newline character \n is a single character. It is not possible to enter the character directly. The \ indicates that you are specifying a special character, and the following letter, an n in this case, specifies which special character.

Display text and the value of an integer:

	printf("We have been in school %d days.\n", dayCount); /*dayCount is a variable*/

The %d in the format string indicates that the printf command should insert the value of the first variable in the argument list, in this case, the value dayCount.

A constant can be used instead of a variable:

	printf("We have been in school %d days.\n", 23);

This constant could also be put directly in the format string instead of the %d.

Different control charactes correspond to different variable types. The %d character can be used with integer variables. Control characters for the various data types are shown in the table below.

int %d float %f double %lf string %s single character %c

a format string may reference several variables. Example statements and their output are shown in the sample code below.

#include <stdio.h>

int main(int argc, char* argv[])
{
    int count = 9;
    float fract = 3.5;
    double percent = 37.6389;
    char singleChar = 'A';
    char * testString = "happy";


    printf("The student's average was: %lf\n", percent);
    /*Output:  The student's average was: 37.638900;*/

    printf("A fraction %f, a string %s and a character %c\n", fract,testString, singleChar);
    /*Output:  A fraction 3.500000, a string happy and a character A*/

    printf("Numbers without spaces %d%lf%f", count, percent, fract);
    /*Output:  Numbers without spaces 937.6389003.500000;*/

    return 0; 
}

next


 home                      table of contents                      about