C Format Specifiers: Beginner-Friendly Guide

In C programming, format specifiers are used to tell the compiler the type of data to expect for input or output. They are mainly used with functions like printf() and scanf().

Let’s break it down step-by-step.

What Are Format Specifiers?

A format specifier starts with a percent sign % followed by a character that represents the data type.

Used in:

  • printf() – to display values

  • scanf() – to receive input from users

List of Common Format Specifiers in C

Format SpecifierData TypeExample ValueUsed With
%d or %iint10printf, scanf
%ffloat3.14printf, scanf
%lfdouble10.89scanf only
%cchar‘A’printf, scanf
%sstring“Hello”printf, scanf
%uunsigned int30000printf, scanf
%ldlong int123456Lprintf, scanf
%luunsigned long123456ULprintf, scanf
%x / %Xhex int0x1Aprintf
%ooctal int075printf
%%Literal %%printf

Example: Using Format Specifiers with printf()

#include <stdio.h>

int main() {
    int age = 25;
    float pi = 3.1415;
    char grade = 'A';
    char name[] = "Alex";

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);
    printf("PI: %.2f\n", pi);   // 2 decimal places
    printf("Grade: %c\n", grade);

    return 0;
}

✅ Output:

Name: Alex Age: 25 PI: 3.14 Grade: A

Example: Using Format Specifiers with scanf()

#include <stdio.h>

int main() {
    int age;
    float height;
    char name[30];

    printf("Enter your name: ");
    scanf("%s", name);

    printf("Enter your age and height: ");
    scanf("%d %f", &age, &height);

    printf("Hello %s, age: %d, height: %.1f\n", name, age, height);
    return 0;
}

Tips for Accurate Usage

  • Always use & with scanf() variables (except for arrays/strings).

  • Match the specifier to the correct data type.

  • Use .2f or .1f for limiting decimal places in floats/doubles.

  • scanf("%s", name) doesn’t need & because arrays decay to pointers.

❌ Common Mistakes to Avoid

MistakeWhat Happens
Using wrong format specifierGarbage value or program crash
Forgetting & in scanf()Runtime error or wrong input
Mismatched typesUnexpected behavior
Printing float with %dIncorrect output

Formatting Tricks

FormatPurposeExample
%.2fPrint 2 decimal places3.14
%5dPrint integer in 5-character space" 25"
%-5dLeft-align in 5-character space"25 "
%02dPrint integer padded with zeros"07"