View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
c tutorial

Explore C Tutorials: From Begi…

  • 132 Lessons
  • 22 Hours

Format Specifiers in C

Updated on 05/02/20254,090 Views


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! 

Commonly Used Format Specifiers in C Programming

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

Format Specifiers in printf() Function

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

Format Specifiers in scanf() Function

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 Format Specifiers

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: Used for signed decimal integers.
  • %i: Used for signed integers (works similar to %d).

%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 Format Specifiers

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

String Format Specifiers

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 in File IO Functions

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.

  • %d: Used for reading or writing integers.
  • %f: Used for reading or writing floats.
  • %s: Used for reading or writing strings.

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 in C with Examples

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.

Specifying Precision and Width for Floating-Point Numbers

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.

  • Precision: Defines how many digits to display after the decimal point.
  • Width: Defines the total number of characters to be printed, including spaces.

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:

  • %.3f: The precision specifier .3f rounds the value of pi to three decimal places.
  • %10.3f: The width 10 ensures that the printed value occupies at least 10 characters, including spaces for alignment.

Formatting Hexadecimal Values

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:

  • %x: Outputs the number in lowercase hexadecimal format.
  • %X: Outputs the number in uppercase hexadecimal format.

Formatting Strings with Width and Alignment

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:

  • %10s: The string str is right-aligned with a width of 10 characters, filling the extra space with spaces.
  • %-10s: The string str is left-aligned with a width of 10 characters, padding the right side with spaces.

Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025

Printing Characters

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:

  • %c: This specifier prints the value of ch as a character.

Printing Strings of Fixed Length

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:

  • %.5s: The .5s specifier limits the output to the first 5 characters of the string.

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.

Things to Avoid in Format Specifiers

Here, we’ll explore some of these pitfalls, how to avoid them, and what can go wrong if you don’t.

1. Buffer Overflow with %s

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

2. Using the Wrong Format Specifier for Data Types

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

3. Not Specifying Precision for Floating Point Numbers

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

4. Using %f for Double Type

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

5. Not Using scanf Format Specifiers Correctly for Strings

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. 

How Well Do You Know Format Specifiers in C? 10 MCQs

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

10. How can you print a hexadecimal value using printf in C?

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.

How Can upGrad Help You Master C Programming?

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?

FAQs

1. What are format specifiers in C programming and why are they important?

A. Format specifiers in C define how data is formatted and interpreted during input and output, ensuring correct data handling.

2. How do format specifiers differ when used with different data types?

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.

3. Why is %f used for both float and double, and is there a difference?

A. %f works for both float and double types, but using %lf explicitly with double ensures maximum precision for double values in C programming.

4. What is the role of width specifiers in C format specifiers?

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.

5. How can I specify precision for floating-point numbers in C?

A. You can use .N to define precision for floating-point numbers, like %.2f to limit the decimal points to two places.

6. What happens if the format specifier does not match the data type?

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.

7. What are some common errors when using format specifiers in C with examples?

A. Common mistakes include mismatching specifiers, forgetting to include width for strings, or incorrectly formatting floating-point numbers, leading to errors or unexpected output.

8. How do format specifiers help in file I/O operations?

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.

9. Why is precision important when using format specifiers for 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.

10. Can I use format specifiers for string manipulation in C?

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.

11. How can I format a double value with a specific number of decimal places in C?

A. To format a double value, use the %f or %lf specifier with precision. For example, %.2lf limits the output to two decimal places.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.