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

Left-aligning with the minus flag

Left-aligning with the minus flag

What you'll learn: How to use the minus sign flag to justify text to the left side of a formatted column.

The Default: Crowding the Right

By default, when you tell printf to reserve a specific amount of space for a value (like %10d), it acts like a shy person in an elevator. It retreats all the way to the right side of the space, leaving the empty "padding" on the left. This is called right-alignment.

While right-alignment is great for columns of numbers that need their decimal points to line up, it looks awkward when you are printing a list of names or labels. If you have a column 20 characters wide, you usually want the word to start at the beginning of the line, not dangle at the end of a long string of spaces.

The Minus Flag: The Leftward Push

To flip this behavior, we use the minus sign (-) immediately after the % symbol. Think of the minus sign as a magnet that pulls your data toward the left margin.

When you write %-10s, you are telling C: "Reserve 10 spaces for this string, but force the text to start at the very first slot. If the text is shorter than 10 characters, put the empty spaces at the end."

See it in Action

Notice the difference in how the columns are structured in this example:

#include <stdio.h>

int main() {
    // Without the minus flag: Right-aligned (Default)
    printf("Default (Right):\n");
    printf("|%10s|%10s|\n", "Item", "Qty");
    printf("|%10s|%10d|\n", "Apples", 5);
    
    printf("\n");

    // With the minus flag: Left-aligned
    printf("With Minus Flag (Left):\n");
    printf("|%-10s|%-10s|\n", "Item", "Qty");
    printf("|%-10s|%-10d|\n", "Apples", 5);

    return 0;
}

In the first block, "Apples" is pushed against the right bar. In the second block, the %-10s flag ensures "Apples" starts immediately after the pipe character, making the list much easier to read—just like a professionally printed receipt or a table in a book.

Key takeaway

Place a minus sign (-) inside your format specifier (e.g., %-15d) to align your output to the left of its reserved space.