Introduction to the printf Function in C
In C programming, the printf function is a fundamental tool for displaying information on the console. It is part of the standard input/output library (<stdio.h>) and is incredibly versatile for printing formatted output.
To output values or print text in C, you can use the printf() function:Example:
#include <stdio.h>
int main() {
printf("Hello World!"); // Prints "Hello World!" to the console using printf.
return 0;
}
Output: Hello World!
Explanation:
- When you are working with text, it must be wrapped inside double quotation marks "".If you forget the double quotes, an error occurs.
- You can use as many printf() functions as you want. However, note that it does not insert a new line at the end of the output.
- If you want to go to the new line you can use "\n".It is called a new line character.
#include <stdio.h>
int main() {
printf("Hello World!\n");
printf("I am learning C.");
return 0;
}
Output : Hellow World!
I am learning C.
- Any characters to be printed after the new line character then appear on the next line of the display.
printf("format string", argument1, argument2, ...);
- Format String: This is a string containing regular characters and format specifiers that define the desired output format.
- Arguments: Values to be formatted and printed, corresponding to the format specifiers in the format string.
int number = 50;
printf("The answer is %d\n", number);
Output: The answer is 50
In this example, %d is a format specifier for an integer, and number is the argument.
float number = 50.1;
printf("The answer is %f\n", number);
Output: The answer is 50.10000
In this example, %f is a format specifier for an float and number is the argument.
Post a Comment