printf() is a standard library function
declared in the header file. It is used to print formatted
output to the standard output device (usually the computer screen or console).
Syntax
printf("format_string", value1, value2, ...);
| Part | Description |
|---|---|
printf |
Name of the output function. |
format_string |
Text along with format specifiers such as %d, %f, %c, and %s. |
value1, value2... |
Variables or values to be displayed. |
Header File
#include
Before using printf(), you must include the
header file because it contains the function
declaration (prototype) of printf().
Example 1: Print a Simple Message
#include
int main()
{
printf("Hello World");
return 0;
}
Output
Hello World
Example 2: Print Variables
#include
int main()
{
int age = 20;
float marks = 89.5;
char grade = 'A';
printf("Age = %d\n", age);
printf("Marks = %.1f\n", marks);
printf("Grade = %c", grade);
return 0;
}
Output
Age = 20
Marks = 89.5
Grade = A
Common Format Specifiers
| Format Specifier | Data Type | Example Output |
|---|---|---|
%d |
Integer | 25 |
%f |
Float | 45.67 |
%c |
Character | A |
%s |
String | Hello |
%lf |
Double | 123.456 |
%x |
Hexadecimal Integer | 1A |
%% |
Percent Symbol | % |
Return Value of printf()
The printf() function returns the total number of characters
successfully printed on the screen.
#include
int main()
{
int result;
result = printf("Hello");
printf("\nCharacters Printed = %d", result);
return 0;
}
Output
Hello
Characters Printed = 5
Advantages of printf()
Advantages
- Displays formatted output.
- Supports multiple data types.
- Easy to use and understand.
- Allows multiple values to be printed in one statement.
- Supports escape sequences such as
\nand\t. - Widely used in debugging and user interaction.
Common Mistakes
Avoid These Mistakes
- Forgetting to include
. - Using the wrong format specifier.
- Passing an incorrect number of arguments.
- Missing quotation marks around text.
Best Practices
- Always include
. - Use the correct format specifier for each data type.
- Use
\nto improve output readability. - Keep output messages meaningful and user-friendly.
Prerequisites
Before Learning This Topic
- Basic understanding of C program structure.
- Knowledge of variables and data types.
- Basic familiarity with functions in C.
- Understanding of header files and the
#includedirective.
Interview Questions
- What is the purpose of the
printf()function? - Which header file contains the declaration of
printf()? - What value does
printf()return? - What is the difference between
printf()andputs()? - What happens if you use the wrong format specifier in
printf()?
Key Takeaway
printf() is a standard library function used to
display formatted output on the console. It is declared in the
header file and supports various data types through
format specifiers. Additionally, it returns the total number of characters
printed, making it useful for both output formatting and certain programming
techniques.