Format Specifiers in C

freeCodeCampfreeCodeCamp
2 min read

Format specifiers define the type of data to be printed on standard output. You need to use format specifiers whether you're printing formatted output with printf() or accepting input with scanf().

Some of the % specifiers that you can use in ANSI C are as follows:

SpecifierUsed For
%ca single character
%sa string
%hishort (signed)
%hushort (unsigned)
%Lflong double
%nprints nothing
%da decimal integer (assumes base 10)
%ia decimal integer (detects the base automatically)
%oan octal (base 8) integer
%xa hexadecimal (base 16) integer
%pan address (or pointer)
%fa floating point number for floats
%uint unsigned decimal
%ea floating point number in scientific notation
%Ea floating point number in scientific notation
%%the % symbol

Examples:

%c single character format specifier:

#include <stdio.h> 

int main() { 
  char first_ch = 'f'; 
  printf("%c\n", first_ch); 
  return 0; 
}

Output:

f

%s string format specifier:

#include <stdio.h> 

int main() { 
  char str[] = "freeCodeCamp"; 
  printf("%s\n", str); 
  return 0; 
}

Output:

freeCodeCamp

Character input with the %c format specifier:

#include <stdio.h> 

int main() { 
  char user_ch; 
  scanf("%c", &user_ch); // user inputs Y
  printf("%c\n", user_ch); 
  return 0; 
}

Output:

Y

String input with the %s format specifier:

#include <stdio.h> 

int main() { 
  char user_str[20]; 
  scanf("%s", user_str); // user inputs fCC
  printf("%s\n", user_str); 
  return 0; 
}

Output:

fCC

%d and %i decimal integer format specifiers:

#include <stdio.h> 

int main() { 
  int found = 2015, curr = 2020; 
  printf("%d\n", found); 
  printf("%i\n", curr); 
  return 0; 
}

Output:

2015
2020

%f and %e floating point number format specifiers:

#include <stdio.h>

int main() { 
  float num = 19.99; 
  printf("%f\n", num); 
  printf("%e\n", num); 
  return 0; 
}

Output:

19.990000
1.999000e+01

%o octal integer format specifier:

#include <stdio.h> 

int main() { 
  int num = 31; 
  printf("%o\n", num); 
  return 0; 
}

Output:

37

%x hexadecimal integer format specifier:

#include <stdio.h> 

int main() { 
  int c = 28; 
  printf("%x\n", c); 
  return 0; 
}

Output:

1c
0
Subscribe to my newsletter

Read articles from freeCodeCamp directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

freeCodeCamp
freeCodeCamp

Learn to code. Build projects. Earn certifications—All for free.