C Format Specifiers

C Tutorial

 C Format Specifiers

In C language, format specifiers tell functions like printf() and scanf() how to interpret and display data.
They are essential for correct input/output, exams, and interviews.


 What Are Format Specifiers?

A format specifier is a special sequence (starting with %) used in formatted I/O to specify the data type.


 Most Common Format Specifiers

 Integer Types

Data TypeSpecifierExample
int%d or %iprintf("%d", a);
short int%hdprintf("%hd", s);
long int%ldprintf("%ld", l);
long long int%lldprintf("%lld", ll);
unsigned int%uprintf("%u", u);
unsigned long%luprintf("%lu", ul);
unsigned long long%lluprintf("%llu", ull);

 Floating-Point Types

Data Typeprintf()scanf()
float%f%f
double%f%lf
long double%Lf%Lf

 


 Character & String Types

Data TypeSpecifierExample
char%cprintf("%c", ch);
char[] (string)%sprintf("%s", str);
  •  For scanf("%s"), no & is needed because arrays already give addresses.

 Special & Advanced Specifiers

PurposeSpecifierExample
Pointer address%pprintf("%p", ptr);
Octal%oprintf("%o", n);
Hex (lower)%xprintf("%x", n);
Hex (upper)%Xprintf("%X", n);
Scientific%e / %Eprintf("%e", d);
General format%g / %Gprintf("%g", d);
Print %%%printf("%%");

 Width & Precision (Very Important)

 Width

 Precision (Decimals)

 Width + Precision


Format Specifiers in scanf()


 

  • Always use & for variables
  • Except arrays/strings

printf() vs scanf() Specifier Differences

Typeprintf()scanf()
int%d%d
float%f%f
double%f%lf
char%c%c
string%s%s

 Common Mistakes

  •  Using %d for float 
  •  Using %f for double in scanf()
  •  Forgetting & in scanf()
  •  Using %s for a single char
  •  Mismatch between variable type & specifier

 Interview Questions (Must Prepare)

  1. Difference between %d and %i

  2. Why %lf is used for double in scanf()?

  3. What is %p used for?

  4. How to print 2 decimal places?

  5. What happens if format specifier mismatches type?


 Summary

  • Format specifiers define how data is read & printed
  •  %d, %f, %c, %s are most common
  • scanf() needs address (&)
  •  Precision and width control output format
  •  Critical for correct I/O, exams & interviews

You may also like...