For working professionals
For fresh graduates
More
Explore C Tutorials: From Begi…
1. Introduction to C Tutorial
2. Addition of Two Numbers in C
3. Anagram Program in C
4. Armstrong Number in C
5. Array in C
6. Array of Pointers in C
7. Array of Structure in C
8. C Program to Find ASCII Value of a Character
9. Assignment Operator in C
10. Binary Search in C
11. Binary to Decimal in C
12. Bitwise Operators in C
13. Boolean in C
14. C Compiler for Mac
15. C Compiler for Windows
16. C Function Call Stack
17. C Language Download
18. Operators in C
19. C/C++ Preprocessors
20. C Program for Bubble Sort
21. C Program for Factorial
22. C Program for Prime Numbers
23. C Program for String Palindrome
24. C Program to Reverse a Number
25. Reverse a String in C
26. C string declaration
27. String Input Output Functions in C
28. Calculator Program in C
29. Call by Value and Call by Reference in C
30. Ceil Function in C
31. Coding Vs. Programming
32. Command Line Arguments in C/C++
33. Comments in C
34. Compilation process in C
35. Conditional Statements in C
36. Conditional operator in the C
37. Constant Pointer in C
38. Constants in C
39. Dangling Pointer in C
40. Data Structures in C
41. Data Types in C
42. Debugging C Program
43. Convert Decimal to Binary in C
44. Define And include in C
45. Difference Between Arguments And Parameters
46. Difference Between Compiler and Interpreter
47. Difference Between If Else and Switch
48. Do While Loop In C
49. Double In C
50. Dynamic Array in C
51. Dynamic Memory Allocation in C
52. Enumeration (or enum) in C
53. Evaluation of Arithmetic Expression
54. Factorial of A Number in C
55. Features of C Language
56. Fibonacci Series Program in C Using Recursion
57. File Handling in C
58. For Loop in C
59. Format Specifiers in C
Now Reading
60. Functions in C
61. Function Pointer in C
62. goto statement in C
63. C Hello World Program
64. Header Files in C
65. Heap Sort in C Program
66. Hello World Program in C
67. History of C Language
68. How to compile a C program in Linux
69. How to Find a Leap Year Using C Programming
70. Identifiers in C
71. If Else Statement in C
72. If Statement in C
73. Implementation of Queue Using Linked List
74. Increment and decrement operators in c
75. Input and Output Functions in C
76. How To Install C Language In Mac
77. Jump Statements in C
78. Lcm of Two Numbers in C
79. Length of an Array in C
80. Library Function in C
81. Linked list in C
82. Logical Operators in C
83. Macros in C
84. Matrix multiplication in C
85. Nested if else statement in C
86. Nested Loop in C
87. One Dimensional Array in C
88. Operator Precedence and Associativity in C
89. Overflow And Underflow in C
90. Palindrome Program in C
91. Pattern Programs in C
92. Pointer to Pointer in C
93. Pointers in C: A Comprehensive Tutorial
94. Pre-increment And Post-increment
95. Prime Number Program in C
96. Program for Linear Search in C
97. Pseudo-Code In C
98. Random Access Files in C
99. Random Number Generator in C
100. Recursion in C
101. Relational Operators in C
102. Simple interest program in C
103. Square Root in C
104. Stack in C
105. Stack Using Linked List in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
112. String Comparison in C
113. String Functions in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
118. Structure of C Program
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
122. Toupper Function in C
123. Transpose of a Matrix in C
124. Two Dimensional Array in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
129. User Defined Functions in C
130. What is Variables in C
131. Is C language case sensitive
132. Fibonacci Series in C
In C programming, format specifiers define how data is displayed when using functions like printf() and scanf(). They help specify the type of data—such as integers, floating-point numbers, or characters—ensuring accurate and structured output.
Without format specifiers, printing variables would lack clarity and consistency, making it harder to interpret program output.
In this tutorial, you’ll explore how format specifiers in C work and how they ensure that your data is displayed precisely.
Let’s dive into the details!
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
Each specifier corresponds to a specific type, ensuring accurate formatting and output. Here's a handy table of the most common format specifiers you'll use:
Format Specifier | Description |
%d or %i | Used for printing signed integers |
%u | Used for printing unsigned integers |
%f | Used for printing floating-point numbers |
%lf | Used for printing double values |
%c | Used for printing a single character |
%s | Used for printing a string |
%x | Used for printing hexadecimal numbers (lowercase) |
%X | Used for printing hexadecimal numbers (uppercase) |
%o | Used for printing octal numbers |
%p | Used for printing a pointer address |
%e | Used for printing floating-point numbers in scientific notation |
%g | Used for printing the most compact form of a floating-point number |
%lld | Used for printing long long integers |
%hd | Used for printing short integers |
The printf() function uses format specifiers to display variables in the desired format. It is used to print different types of data, such as integers, floats, strings, etc. The appropriate specifier for each type ensures proper formatting in the output.
Example:This example demonstrates the usage of different format specifiers to print integer, float, and string values.
#include <stdio.h>
int main() {
int num = 10;
float price = 99.99;
char name[] = "Laptop";
printf("Product: %s\n", name); // %s for string
printf("Price: %.2f\n", price); // %.2f for float (rounded to 2 decimal places)
printf("Quantity: %d\n", num); // %d for integer
return 0;
}
Output:
Product: LaptopPrice: 99.99Quantity: 10
The scanf() function is used to read input from the user and store it in variables of the required type. Format specifiers in C Programming in scanf() define how the input should be interpreted and assigned to variables.
Using the correct format specifiers in scanf() is crucial because they ensure accurate data input and prevent undefined behavior.
Let's look at an example.This program uses scanf() to read user input and store it in integer and float variables.
#include <stdio.h>
int main() {
int age;
float percent;
printf("Enter Age and Percent: \n");
scanf("%d %f", &age, &percent); // %d for integer, %f for float
printf("Age: %d Percent: %.2f\n", age, percent);
return 0;
}
Output:
Enter Age and Percent: Age: 25 Percent: 85.50
Integer specifiers are used to print or read integer types. The most common format specifiers for integers are %d and %i, both of which work similarly. They can handle decimal values.
%d and %i both read integers in scanf(), but %i can interpret numbers in different bases (decimal, octal, hexadecimal) based on prefixes (0 for octal, 0x for hex), while %d always treats input as decimal.
Example:
int age = 30;
printf("Age: %d\n", age);
Output:
Age: 30
Floating-point specifiers are used to print floating-point numbers, including both single-precision (float) and double-precision (double) values.
In printf(), %f is used for both float and double (as float is promoted to double), but in scanf(), %f is for float, while %lf should be used for double.
Example:
float price = 12.345;
printf("Price: %.2f\n", price);
Output:
Price: 12.35
For displaying strings, you use the %s format specifier, which is used with printf() to display a string stored in a character array or pointer.
Example:
char name[] = "Jai Sharma";
printf("Name: %s\n", name);
Output:
Name: Jai Sharma
Also Read: What is Array in C? With Examples
Format Specifiers also play a critical role in file handling. When reading from or writing to files, format specifiers are used similarly to how they are used in scanf() and printf() for standard input/output. They control how data is read from or written to a file.
Example:
FILE *file = fopen("data.txt", "w");
int number = 100;
fprintf(file, "Number: %d\n", number);
fclose(file);
Output:
The output in data.txt would be: Number: 100
Once you’re comfortable with basic format specifiers in C programming, dive into more advanced ones.
Advanced format specifiers are needed for precise control over data formatting, handling complex data types, localization, and ensuring accurate input/output in real-world applications.
They allow you to control how data is formatted when printed, providing greater flexibility in formatting. These include specifying precision and width for floating-point numbers, handling hexadecimal values, and formatting strings with more control.
Let’s explore these advanced format specifiers, starting with the precision and width specifiers.
You can control the number of digits displayed after the decimal point (precision) and the total width of the printed number (width). For example, %e is used to print numbers in scientific notation, allowing you to specify both precision and width for such values.
Example:
#include <stdio.h>
int main() {
double pi = 3.14159265359;
printf("Pi with 3 decimal places: %.3f\n", pi); // Precision to 3 decimal places
printf("Pi with width 10 and 3 decimal places: %10.3f\n", pi); // Width 10 and Precision 3
return 0;
}
Output:
Pi with 3 decimal places: 3.142Pi with width 10 and 3 decimal places: 3.142
Explanation:
The %x and %X format specifiers are used for printing integers in hexadecimal format. %x prints in lowercase letters, while %X prints in uppercase letters.
Example:
#include <stdio.h>
int main() {
int num = 255;
printf("Hexadecimal (lowercase): %x\n", num); // Output in lowercase hexadecimal
printf("Hexadecimal (uppercase): %X\n", num); // Output in uppercase hexadecimal
return 0;
}
Output:
Hexadecimal (lowercase): ffHexadecimal (uppercase): FF
Explanation:
Strings can be formatted with specified width, where the text will be padded with spaces to fit within the given width. You can also specify left or right alignment using - for left alignment.
For wide characters (e.g., Unicode), use %ls to ensure proper handling and formatting.
Example:
#include <stdio.h>
int main() {
char str[] = "Hello";
printf("Right-aligned: %10s\n", str); // Right-aligned with width 10
printf("Left-aligned: %-10s\n", str); // Left-aligned with width 10
return 0;
}
Output:
Right-aligned: HelloLeft-aligned: Hello
Explanation:
Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025
The %c format specifier is used to print a single character. This is a simple but useful specifier when dealing with individual characters. For example, printf("%c", 65); prints the character 'A', as it uses the ASCII value for 'A'.
Example:
#include <stdio.h>
int main() {
char ch = 'A';
printf("Character: %c\n", ch); // Output a single character
return 0;
}
Output:
Character: A
Explanation:
When working with strings, you may need to limit the number of characters printed. This is done by specifying the maximum number of characters to be printed in the format specifier.
Example:
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
printf("First 5 characters: %.5s\n", str); // Prints the first 5 characters of the string
return 0;
}
Output:
First 5 characters: Hello
Explanation:
While format specifiers are powerful tools in C programming, improper usage can lead to unexpected behavior.
Let’s look at some common mistakes and issues to avoid when working with them.
Here, we’ll explore some of these pitfalls, how to avoid them, and what can go wrong if you don’t.
One of the most common issues when using format specifiers is the risk of buffer overflow when using the %s specifier to read strings. The %s specifier does not limit the number of characters it reads, so if you input a string longer than the allocated space in memory, it can overwrite adjacent memory, causing undefined behavior or even crashes.
Example:
#include <stdio.h>
int main() {
char str[5];
printf("Enter a string (up to 4 characters): ");
scanf("%s", str); // Potential buffer overflow if input exceeds 4 characters
printf("You entered: %s\n", str);
return 0;
}
Output:
Enter a string (up to 4 characters): HelloYou entered: Hell
Explanation:
In the code above, the buffer str has space for 5 characters, but we haven’t limited the input to avoid overflow. Entering "Hello" (which is 5 characters) would overwrite memory beyond str and may result in unexpected behavior.
Fix: Always limit the input size with a width specifier. Use %4s to read only 4 characters, which leaves room for the null terminator.
Using fgets() is a safer alternative to scanf("%s"), as it allows you to specify a maximum input length, preventing overflow.
Safe Code: scanf("%4s", str); // Limits input to 4 characters to prevent buffer overflow
A common mistake with format specifiers is using the wrong specifier for the data type, which can lead to undefined behavior, crashes, or incorrect output.
For instance, using %d to read a floating-point value or %f to read an integer value can cause data corruption or crashes.
Example:
#include <stdio.h>
int main() {
float f = 3.14;
printf("Enter an integer: ");
scanf("%d", &f); // Incorrect: %d is for integers, not floating-point numbers
printf("You entered: %.2f\n", f);
return 0;
}
Output:
Enter an integer: 10You entered: 10.00
Explanation:
In this case, the program asks for an integer but tries to store it in a float variable using %d. This mismatch leads to incorrect behavior when printing the value with %.2f, and the expected value is distorted.
Fix: Use the correct format specifiers for the corresponding types. In this case, the correct format specifier for a float is %f, not %d.
Safe Code:
scanf("%f", &f); // Correct: Use %f to read a float value
Also Read: Data Types in C and C++ Explained for Beginners
When printing floating-point numbers, it's essential to specify the precision (number of decimal places) you want. Otherwise, the output may be too long or lack the precision you need.
Example:
#include <stdio.h>
int main() {
float pi = 3.14159265359;
printf("Pi value: %f\n", pi); // Default float precision, 6 decimal places
return 0;
}
Output:
Pi value: 3.141593
Explanation:
By default, %f prints floating-point numbers with 6 decimal places, which may not always be desirable. If you need to control the precision, use the %.2f specifier for two decimal places.
Fix: Define the precision explicitly when working with floating-point numbers.
Safe Code:
printf("Pi value: %.2f\n", pi); // Prints Pi value with 2 decimal places
In C, double and float are two distinct data types. While %f works for both in printf(), it doesn't fully utilize the precision of double. For scanf(), however, %f is used for float, and %lf should be used for double to correctly handle the input.
Example:
#include <stdio.h>
int main() {
double d = 3.141592653589793;
printf("Double value: %f\n", d); // Works but won't give maximum precision for double
return 0;
}
Output:
Double value: 3.141593
Explanation:
For the best precision with double, use %lf instead of %f to indicate you are working with a double value. While %f also works for double, it’s more precise when using %lf.
Fix: Use the %lf format specifier for double values.
Safe Code:
printf("Double value: %lf\n", d); // Correct way to print a double with more precision
While using scanf to input strings, one common mistake is to forget the width specifier. Without it, scanf could read more characters than the allocated space in memory, resulting in buffer overflow. A safer alternative is using fgets(), which allows you to specify the maximum number of characters to read, preventing overflow.
Example:
#include <stdio.h>
int main() {
char name[10];
printf("Enter your name: ");
scanf("%s", name); // Potential buffer overflow if input exceeds 9 characters
printf("Hello, %s\n", name);
return 0;
}
Output:
Enter your name: JonathanDoeHello, Jonatha
Explanation:
If you input a string longer than the buffer size (9 characters + 1 for null terminator), scanf will overflow the memory allocated for name, leading to truncation or potential crashes.
Fix: Always specify the maximum width to prevent overflow. For example, %9s will limit the input to 9 characters, leaving space for the null terminator.
Safe Code:
scanf("%9s", name); // Ensures input is safely limited to 9 characters
Always use format specifiers with care, as they play a crucial role in managing how data is interpreted, formatted, and displayed.
This quiz will challenge your understanding of format specifiers in C. From the basics to more advanced uses, let’s test your knowledge of how data types are handled and formatted in C programming!
1. Which format specifier is used to print an integer in C?
A) %f
B) %d
C) %c
D) %s
2. What is the correct format specifier to print a floating-point number in C?
A) %d
B) %lf
C) %i
D) %f
3. What format specifier is used to print a character in C?
A) %d
B) %c
C) %s
D) %p
4. Which of the following format specifiers is used for printing a string in C?
A) %c
B) %s
C) %i
D) %u
5. How do you print a pointer address using the printf function in C?
A) %p
B) %x
C) %u
D) %d
6. What will be the output of the following C code?
int num = 10;
printf("%d\n", num);
A) 10
B) num
C) Undefined output
D) 0
7. What is the correct format specifier to print a long integer in C?
A) %li
B) %d
C) %ld
D) %lf
8. What does the * width modifier in a format specifier do in C?
A) It automatically scales the output value
B) It allows dynamic field width for the output
C) It specifies the number of decimal places
D) It ensures that the output value fits within a given range
9. What will the following C code print?
float value = 3.14159;
printf("%.2f\n", value);
A) 3.14159
B) 3.14
C) 3
D) 3.142
A) %h
B) %x
C) %f
D) %d
Understanding factorial calculations is just the beginning—keep building your C programming skills with expert-led courses and hands-on learning.
upGrad offers in-depth courses designed to enhance your knowledge of C programming, including the proper use of format specifiers. From learning to print integers, strings, and floating-point numbers, to mastering more advanced formatting techniques, upGrad's structured courses ensure you gain hands-on experience in handling C's powerful formatting tools.
Explore upGrad’s courses to deepen your understanding of C programming:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Understanding Definitions and Includes in C
Difference between Argument and Parameter in C/C++ with Examples
Compiler vs. Interpreter in Programming
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Constants in C Explained
Find Out About Data Structures in C and How to Use Them?
A. Format specifiers in C define how data is formatted and interpreted during input and output, ensuring correct data handling.
A. Each data type requires a specific format specifier. For example, %d for integers and %f for floats, ensuring the correct representation of the data.
A. %f works for both float and double types, but using %lf explicitly with double ensures maximum precision for double values in C programming.
A. Width specifiers allow you to control the number of characters printed. For instance, %5d ensures the integer is printed in a field of at least five characters.
A. You can use .N to define precision for floating-point numbers, like %.2f to limit the decimal points to two places.
A. Using the wrong specifier can lead to undefined behavior or incorrect output. For example, using %d for a float can result in garbage values.
A. Common mistakes include mismatching specifiers, forgetting to include width for strings, or incorrectly formatting floating-point numbers, leading to errors or unexpected output.
A. Format specifiers control how data is read and written from files, ensuring correct formatting during input and output operations. For example, %f can be used to read or write floating-point numbers.
A. Precision ensures that the correct number of decimal places is displayed, especially for scientific calculations. It avoids rounding errors by controlling the number of digits.
A. Yes, format specifiers like %s are used to handle strings in both input and output. You can also limit the string size using a width specifier.
A. To format a double value, use the %f or %lf specifier with precision. For example, %.2lf limits the output to two decimal places.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.