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

Basic field width formatting

Basic field width formatting

What you'll learn: How to reserve a specific amount of space for your data to create neatly aligned columns in your output.

The "Parking Space" Analogy

When you use printf to display a number or a word, C uses exactly as much space as the data needs. If you print the number 5, it takes one character space. If you print 500, it takes three. This becomes a headache when you try to print a list of items; the numbers will jump around and look messy because they aren't lined up.

Think of field width as a reserved parking space. Even if you are driving a tiny bicycle, if the parking spot is 10 feet wide, the bicycle still occupies that 10-foot block. By setting a field width, you tell C: "No matter how small this piece of data is, give it at least this many characters of room."

How to Set Width

To set a field width, you place a number between the % sign and the type specifier (like d for integers). For example, %5d tells C to print an integer with a minimum width of 5 characters.

If the number you are printing is smaller than the width (like the number 42 in a %5d spot), C will pad the left side with empty spaces. If the number is larger than the width, C won't cut it off—it will overflow the boundary to ensure the data remains accurate.

Seeing it in Action

Observe how the numbers below align perfectly on the right side because we’ve given them all the same "parking space" size:

#include <stdio.h>

int main() {
    // Printing headers
    printf("Item ID   Price\n");
    
    // Using %7d to reserve 7 spaces for the ID
    // Using %8d to reserve 8 spaces for the Price
    printf("%7d %8d\n", 1, 500);
    printf("%7d %8d\n", 25, 12000);
    printf("%7d %8d\n", 350, 5);

    return 0;
}

In the output, the IDs and Prices will form neat columns. Because they are right-aligned by default, the "ones" column of every number will line up vertically, making the list much easier for a human to read.

Key takeaway

Add a number between % and your type letter to reserve a minimum number of character spaces for your data.