Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C Output (printf)

To show something on the screen, C programs use the printf function from stdio.h. The name means print formatted: besides fixed text, it can print the values of variables in a format you choose.

Printing text

printf prints exactly what is between the double quotes. It does not add a new line by itself, so two calls without \n continue on the same line:

#include <stdio.h>

int main(void) {
    printf("Hello ");
    printf("World");
    printf("\n");
    printf("This is a new line.\n");
    return 0;
}
Output
Hello World
This is a new line.

Printing numbers

To print a value, put a format specifier in the text where the value should appear, and give the value after a comma. %d prints a whole number (an int):

#include <stdio.h>

int main(void) {
    printf("%d\n", 42);
    printf("Sum: %d\n", 7 + 5);
    printf("%d apples and %d oranges\n", 3, 8);
    return 0;
}
Output
42
Sum: 12
3 apples and 8 oranges

The values are used in order: the first %d takes the first value, the second %d the second. The Format Specifiers topic shows the codes for decimals, characters and text.

Special characters

Some characters cannot be typed directly inside quotes. They are written with a backslash, as an escape sequence:

EscapeMeaning
\nnew line
\ttab (jumps to the next column)
\"a double quote
\\a backslash
#include <stdio.h>

int main(void) {
    printf("Name\tAge\n");
    printf("Asha\t12\n");
    printf("She said \"hi\".\n");
    printf("C:\\temp\n");
    return 0;
}
Output
Name	Age
Asha	12
She said "hi".
C:\temp

To print a percent sign itself, write %%, because a single % starts a format specifier.

puts

puts("text") prints a line of text and adds the newline for you. It is handy for fixed text; use printf when you need values or no newline.

Practice exercises

  1. Print a small table of three fruits and their prices with \t between the columns.
  2. Print the sentence 50% of 8 is 4 using %d for the numbers and %% for the percent sign.
  3. Print the path C:\Users\student exactly as written.