CodeBlanks Logo Icon CodeBlanks

printf and escapes

Learn formatted output with printf and escape sequences.

printf and format specifiers

The printf function writes formatted text to the screen. Format specifiers tell how to print variables:

  • %d: integer
  • %f: floating-point number
  • %s: string
  • %c: character

Escape sequences represent special characters: \n new line, \t tab, \\ backslash.

Multiple specifiers

You can print multiple variables in a single printf call. The order of specifiers must match the order of arguments:

int age = 25;
double height = 1.75;
printf("Age: %d, Height: %f", age, height);

Output: Age: 25, Height: 1.750000

The number of specifiers must match the number of arguments; otherwise undefined behavior occurs.

Practice Write formatted output

Print int n = 5; as Result: 5 using printf. Use the %d specifier.

Starter code

main.c
// print Result: 5 with printf

Sample solution

main.c
#include <stdio.h>

int main(void) {
    int n = 5;
    printf("Result: %d", n);
    return 0;
}

Expected output

Result: 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does \n mean?

  • Tab space
  • New line Correct answer
  • Backspace
  • Quote mark

Explanation: \n means new line; it moves the cursor to the next line.

2 Integer specifier

Question
printf("Result: ____", 5);
Answer
printf("Result: %d", 5);

Explanation: %d is the specifier used for integers.

3 What does printf("%d %d", a, b); print?

  • Only b is printed
  • Only a is printed
  • Two integers separated by space Correct answer
  • It errors out

Explanation: %d %d prints two integers separated by a space.

All lessons in Beginner