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

Printing integers with `%d`

Printing integers with %d

What you'll learn: How to use the %d format specifier to display whole numbers inside a text string.

In C, the printf() function is your primary way to talk to the user. However, if you want to print a number stored in a variable, you can’t just drop the variable name into the quotes. If you type printf("My age is age");, the computer will literally print the word "age." To fix this, we use a special placeholder called a format specifier.

The Mail Slot Analogy

Think of a string of text like a pre-printed postcard with a blank space left for a specific piece of information. The %d symbol acts like a mail slot or a "reserved seat" within your sentence. When the program runs, it looks at the %d, rushes to the end of the line to see which variable you provided, and plugs that number into the slot.

The d in %d stands for "decimal," which is the standard way we represent whole numbers (integers) like 5, 42, or -10.

How the Syntax Works

To use it, you provide two parts to printf:

  1. The format string (the text inside quotes containing %d).
  2. The variable that holds the value you want to show.
#include <stdio.h>

int main() {
    int score = 95;
    int lives = 3;

    // The first %d is replaced by score, the second by lives
    printf("Game Over! Your score is %d and you had %d lives left.\n", score, lives);

    return 0;
}

In the example above, the order is crucial. The computer matches the first %d with the first variable after the comma (score), and the second %d with the second variable (lives). If you swap the variables, the numbers in your sentence will be swapped too!

Why This Matters

Computers treat "text" and "numbers" very differently in memory. The %d specifier tells C: "Take this binary data, turn it into a readable human number, and stitch it into this sentence." Without it, your program wouldn't know how to translate your data into something a person can read on a screen.

Key takeaway

Use the %d placeholder inside your quotes to reserve a spot for an integer variable.