More printf Tricks

Width: making columns

Put a number between % and the letter to give the value a minimum width. C fills the rest with spaces on the left. This is great for tables:

#include <stdio.h>

int main() {
    printf("[%5d]\n", 42);
    printf("[%5d]\n", 1234);
    printf("[%8.2f]\n", 3.14159);
    return 0;
}

Output

[   42]
[ 1234]
[    3.14]

A minus sign moves the value to the left instead:

#include <stdio.h>

int main() {
    printf("[%-5d]\n", 42);
    printf("%-8s%5d\n", "Apples", 3);
    printf("%-8s%5d\n", "Kiwis", 12);
    return 0;
}

Output

[42   ]
Apples      3
Kiwis      12

Tip: %s prints text (a string). We'll use it a lot later.

Leading zeros

Put a 0 before the width to fill with zeros instead of spaces – handy for times and codes:

#include <stdio.h>

int main() {
    int hours = 9;
    int minutes = 5;
    printf("%02d:%02d\n", hours, minutes);
    printf("Order #%05d\n", 42);
    return 0;
}

Output

09:05
Order #00042

Printing a % sign

Because % starts a placeholder, write %% to print one real percent sign:

#include <stdio.h>

int main() {
    int battery = 80;
    printf("Battery: %d%%\n", battery);
    return 0;
}

Output

Battery: 80%

The placeholder must match the type

printf trusts you. If you use the wrong placeholder, it prints nonsense. Always match them:

ValueUse
int%d
double / float%f
char%c
text (string)%s

Common mistake: Printing a double with %d (or an int with %f). C won't stop you, but the output will be a strange wrong number.

HOME LABS COMMUNITY DASHBOARD