Outputs¶
This section focuses on the printf() function for displaying output in C programming.
printf() Function¶
The printf() function is used to display text, numbers, or other data on the console. It is part of the standard input/output library (stdio.h), which must be included at the top of your program:
Basic Syntax¶
- Format string: The text to display, which may include placeholders (format specifiers) for variables.
- Arguments: The values or variables to be inserted into the format string.
Example: Basic Output¶
Output:
Explanation:
"Hello, World!"is the text to print.\nadds a new line after the text.
Printing Variables¶
printf() can display variable values using format specifiers (covered previously).
Example: Printing Variables¶
Output:
Common Mistakes¶
- Forgetting
\n: Without it, the next output may appear on the same line. - Missing
stdio.h: Always include#include <stdio.h>forprintf()to work. - Mismatched Arguments: Ensure the number of format specifiers matches the arguments.
Example: Incorrect vs. Correct¶
#include <stdio.h>
int main() {
int num = 42;
// Incorrect: Missing argument
printf("Number: %d\n");
// Correct
printf("Number: %d\n", num);
return 0;
}
Output:
Summary¶
- Use
printf()to display text and variables in C. - Include escape sequences like
\nand\tfor formatting. - Ensure
#include <stdio.h>is present and arguments match format specifiers.