How to Format Output in C: Simple Guide with Examples
In C, you format output using the
printf function with format specifiers like %d for integers, %f for floating-point numbers, and %s for strings. These specifiers tell printf how to display the values you provide.Syntax
The basic syntax for formatting output in C uses the printf function:
printf("format string", values...);- The format string contains text and format specifiers that start with
%. - Each format specifier corresponds to a value you want to print.
Common format specifiers include:
%d- integer%f- floating-point number%c- single character%s- string
c
printf("format string", values...);
Example
This example shows how to print an integer, a floating-point number, and a string using printf with format specifiers.
c
#include <stdio.h> int main() { int age = 25; float height = 5.9f; char name[] = "Alice"; printf("Name: %s\n", name); printf("Age: %d years\n", age); printf("Height: %.1f feet\n", height); return 0; }
Output
Name: Alice
Age: 25 years
Height: 5.9 feet
Common Pitfalls
Common mistakes when formatting output in C include:
- Using the wrong format specifier for the data type (e.g.,
%dfor a float). - Forgetting to include
\nfor a new line, which can make output hard to read. - Not matching the number of format specifiers with the number of values.
c
#include <stdio.h> int main() { float pi = 3.14f; // Wrong: using %d for float // printf("Pi is %d\n", pi); // This causes incorrect output // Right: use %f for float printf("Pi is %f\n", pi); return 0; }
Output
Pi is 3.140000
Quick Reference
| Format Specifier | Description | Example |
|---|---|---|
| %d | Prints an integer (int) | printf("%d", 10); // prints 10 |
| %f | Prints a floating-point number (float, double) | printf("%f", 3.14); // prints 3.140000 |
| %.1f | Prints float with 1 decimal place | printf("%.1f", 3.14); // prints 3.1 |
| %c | Prints a single character | printf("%c", 'A'); // prints A |
| %s | Prints a string | printf("%s", "Hello"); // prints Hello |
| \n | New line character | printf("Hello\nWorld"); // prints Hello and World on separate lines |
Key Takeaways
Use printf with format specifiers like %d, %f, and %s to format output in C.
Match each format specifier with the correct data type to avoid wrong output.
Include \n to add new lines for clearer output.
Use precision like %.1f to control decimal places for floating-point numbers.
Always check that the number of format specifiers matches the number of values.