The printf() function in C is used to output formatted text to the standard output, typically the console. Here's how it works:
Function Prototype:
int printf(const char *format, ...);
Parameters:
format: A string that specifies how subsequent arguments (if any) are to be formatted. It can include format specifiers that dictate how to display the values....: A variable number of arguments that correspond to the format specifiers in the format string.
Format Specifiers:
Common format specifiers include:
%d: Integer%f: Floating-point number%c: Character%s: String%x: Hexadecimal integer
How It Works:
- Format String: The first argument is the format string, which can contain plain text and format specifiers.
- Variable Arguments: The subsequent arguments are the values to be formatted and printed according to the format specifiers.
- Output:
printf()processes the format string, replaces the format specifiers with the corresponding values, and sends the resulting string to the standard output.
Example:
Here’s an example demonstrating how printf() works:
#include <stdio.h>
int main() {
int age = 25;
float height = 5.9;
char initial = 'A';
char name[] = "Alice";
printf("Name: %s\n", name); // Output: Name: Alice
printf("Initial: %c\n", initial); // Output: Initial: A
printf("Age: %d\n", age); // Output: Age: 25
printf("Height: %.1f feet\n", height); // Output: Height: 5.9 feet
return 0;
}
Explanation of the Example:
- The format string contains text and format specifiers.
- Each format specifier is replaced by the corresponding variable's value when
printf()is called. - The output is displayed on the console in a formatted manner.
Return Value:
printf() returns the total number of characters printed (excluding the null byte used to end output to strings). If an error occurs, it returns a negative value.
This is how printf() works to display formatted output in C programs.
