C Format Specifiers: Beginner-Friendly Guide

Format specifiers in C tell the compiler what type of data to expect when printing or scanning values using printf() and scanf() functions.

They ensure that the correct data type is formatted properly.

Why Are Format Specifiers Important?

When you use printf() or scanf(), the format specifier helps match the variable type so that the value is displayed or read correctly.

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

Format Specifiers with Examples in C

Format SpecifierData TypeUsed WithExample Output
%dintprintf, scanf10
%ffloatprintf, scanf10.500000
%ccharprintf, scanfA
%sstring (char array)printf, scanfHello
%lfdoubleprintf, scanf12.345678
%uunsigned intprintf4294967295
%x / %Xhexadecimalprintfa / A
%ooctalprintf12 (octal of 10)
%pmemory addressprintf0x7ffee3ac4c90
%%percentage signprintf%

 

Example: Using %d, %f, %c

#include <stdio.h>

int main() {
    int age = 25;
    float height = 5.9;
    char grade = 'A';

    printf("Age: %d\n", age);
    printf("Height: %f\n", height);
    printf("Grade: %c\n", grade);

    return 0;
}

 Output:

Age: 25
Height: 5.900000
Grade: API: 3.14

 

Example: Using %s and %lf

#include <stdio.h>

int main() {
    char name[] = "Alice";
    double balance = 12345.67;

    printf("Name: %s\n", name);
    printf("Balance: %lf\n", balance);

    return 0;
}

Field Width and Precision

FormatMeaning
%10dPrint integer in 10-width field
%.2fPrint float with 2 decimals
%10.3fFloat: width 10, 3 decimal places
printf("%10.2f", 123.456);  // Output: "    123.46"

scanf() and Format Specifiers

int num;
float rate;
char letter;

scanf("%d %f %c", &num, &rate, &letter);

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

MistakeProblem
Using wrong specifierGarbage output or compiler warning
Forgetting & in scanf()Causes runtime errors
Mismatched data typeMay crash or behave unexpectedly

 

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"

Best Practices

TipWhy It’s Important
Use the correct format for the dataEnsures correct output and memory usage
Use precision for floating valuesImproves readability
Always test input/outputPrevents bugs during runtime