C Output

Showing results on the screen is one of the first things you want a program to do. In C, that job belongs to the printf function.

The printf function is your main tool for output in C. The name stands for "print formatted". You give it text inside double quotes, and it sends that text to the screen.

Basic output

#include <stdio.h>

int main() {
    printf("Welcome to C output!");
    return 0;
}

Printing More Than Once

You can call printf as many times as you like. By default the pieces of text are joined together on the same line, because printf does not add a line break on its own.

Two calls, one line

#include <stdio.h>

int main() {
    printf("Learning C ");
    printf("is fun!");
    return 0;
}

Printing Numbers

To print a number, you use a format specifier inside the text. The specifier %d is replaced by the whole number you pass after the text.

Text plus a number

#include <stdio.h>

int main() {
    printf("I have %d apples", 5);
    return 0;
}
SpecifierUsed for
%dWhole numbers (integers)
%fNumbers with a decimal point
%cA single character
%sA piece of text (a string)
Note: The text inside the double quotes is called a string. Everything between the quotes is printed exactly as written, except for special codes like %d.
Note: Notice the space at the end of "Learning C " in the earlier example. Spaces inside the quotes are printed too, so they are how you keep words from running together.

Exercise: C Output

Which function is used to display output to the screen in C?