Course contentsShow
← C
Lesson 49 of 1,2191. FoundationsFree lesson

Introduction to Format Specifiers

Introduction to Format Specifiers

What you'll learn: You will learn how to use placeholders to display different types of data, like numbers and text, inside your program's output.

The Mail Slot Analogy

Imagine you are writing a form letter. You might leave a blank space that says [Name Goes Here] or [Date Goes Here]. When the letter is printed, you swap those brackets for real information.

In C, the printf function works the same way. It cannot simply guess what a variable is; you have to tell it exactly where a value should go and what kind of value it is. We do this using format specifiers, which are special codes starting with a percent sign (%).

Meeting the Big Three

While there are many specifiers, you will spend 90% of your time with these three:

  1. %d: Used for integers (whole numbers like 5, -42, or 0). Think of "d" for "decimal integer."
  2. %f: Used for floats (numbers with decimal points like 3.14). Think of "f" for "floating point."
  3. %c: Used for a single character (like 'A' or '$').

How to Code It

When you use a specifier, you put it inside the quotation marks. Then, after the comma, you provide the data you want to "plug in" to that spot. C will match them up in the order they appear.

#include <stdio.h>

int main() {
    // Printing a whole number
    printf("I am %d years old.\n", 25);

    // Printing a decimal number
    printf("The price is %f dollars.\n", 19.99);

    // Printing a character
    printf("The grade is %c.\n", 'A');

    return 0;
}

Why Precision Matters

If you try to use %d for a decimal number like 19.99, the computer gets confused. It’s like trying to fit a square peg in a round hole—the program might crash or show a nonsensical number. Always match the specifier to the type of data you are holding. Think of the specifier as a reserved seat at a theater; you must have the right ticket to sit in that specific spot.

Key takeaway

Format specifiers like %d and %f act as placeholders that tell printf exactly where and how to display your data.