Course contentsShow
← C
Lesson 685 of 1,21910. Input and OutputFree lesson

Specifying field width for alignment

Specifying field width for alignment

What you'll learn: How to use numbers in your format specifiers to create neatly aligned columns and tables in your console output.

The problem with standard printing

By default, printf only uses as much space as it needs. If you print the number 5, it uses one character space. If you print 500, it uses three. When you are trying to print a list of data—like a receipt or a high-score table—this causes your text to stagger and look messy. Imagine trying to read a spreadsheet where the columns shift left and right depending on how big the numbers are; it would be a headache!

Setting the field width

To fix this, you can specify a field width. This tells C, "I want this piece of data to take up at least this many spaces."

You do this by placing a number between the percent sign (%) and the type letter (like d or f). For example, %5d means "print an integer and make sure it occupies at least 5 spaces."

Think of this like a parking spot. If your car (the data) is smaller than the spot, printf adds empty spaces (padding) to the left to fill the gap. If your car is larger than the spot, C won't cut your data off—it will just push past the boundary to ensure the value remains readable.

Alignment in action

By using the same width for every row in a column, you create a perfectly straight vertical line. By default, the text is right-aligned (padded on the left). If you want left-alignment, simply put a minus sign (-) before the number.

#include <stdio.h>

int main() {
    // Printing a simple header
    printf("%-10s %8s\n", "ITEM", "PRICE");
    printf("--------------------------\n");

    // %-10s means left-align in a 10-character block
    // %8d means right-align in an 8-character block
    printf("%-10s %8d\n", "Apples", 5);
    printf("%-10s %8d\n", "Bananas", 120);
    printf("%-10s %8d\n", "Cherries", 1500);

    return 0;
}

In the example above, "Apples" and "Cherries" both start at the same left-hand position, while the prices are neatly tucked against the right side, keeping the units, tens, and hundreds places perfectly stacked.

Key takeaway

Add a number inside your % specifier (like %10d) to set a minimum width, creating "invisible columns" for clean, professional output.