C ยท Chapter 5 of 45

C Output (printf)

The printf() function is used to print output to the screen. It is part of the standard input/output library, so you must include <stdio.h> to use it.

printf uses format specifiers like %d for integers, %f for floats, %c for characters, and %s for strings to insert variable values into the output text.

Syntax
printf("format string", values...);

Format specifiers

Common specifiers include %d (int), %f (float/double), %c (char), %s (string), and %p (pointer). The specifier must match the type of the value being printed.

Escape sequences

Special characters like newline (\n) and tab (\t) let you control formatting inside strings. \\ prints a literal backslash and \" prints a literal quote.

Example 1 (c)
#include <stdio.h>

int main() {
  int age = 30;
  printf("Age: %d\n", age);
  return 0;
}
Output
Age: 30

%d is replaced by the integer value of age.

Example 2 (c)
#include <stdio.h>

int main() {
  printf("Name: %s, Score: %.1f\n", "Amy", 9.5);
  return 0;
}
Output
Name: Amy, Score: 9.5

%s prints a string and %.1f prints a float with one decimal place.

Key points

  • printf() requires #include <stdio.h>.
  • Format specifiers must match the argument type.
  • \n creates a new line in the output.
  • Multiple values can be printed in one printf call.
๐Ÿ’ก Note: Mismatching a format specifier and argument type is undefined behavior and a common source of bugs.

๐Ÿ“ Quick Quiz

1. Which header is required for printf()?

2. Which specifier is used for a float value?

3. What does \n do inside a string?