![]() |
VOOZH | about |
In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen).
Hi!
Explanation: In this program, the printf function print the text "Hi!" on the console screen.
The printf() function is defined inside <stdio.h> header file.
Parameter:
Return Value:
In addition to working as placeholders, format specifiers can also contain a few more instructions to manipulate how the data is displayed in the output.
The below examples demonstrate the use of printf() in our C program for different purposes.
Sum of 99 and 1 is 100
Explanation: In this program, the format specifier %d is used to print integers variables using printf. Here, it prints the values of a, b, and the result of a + b.
Sum of 99 and 1 is 100
Explanation: The format specifier %d is used to print integer literals. It substitutes 99, 1, and the result of 99 + 1 into the string.
We can right align the output using the width specifier with positive value.
Welcome to GfG!
Explanation: The format specifier %40s prints the string s right-aligned with a minimum width of 40 characters. If the string is shorter than 40 characters, it is padded with spaces on the left.
If we pass negative width, the minimum width will be the absolute value of the width, but the text will be left aligned.
Welcome to GfG! Geeks
Explanation: The format specifier %-50s prints the string s left-aligned with a minimum width of 50 characters. The remaining spaces are padded with blanks, followed by printing Geeks.
The precision sub-specifier adds leading zeroes to the integer.
0000002451
Explanation: The format specifier %.10d ensures the integer n is printed with a precision of 10 digits. If n has fewer digits, it is left-padded with zeros to meet the required precision.
For floating point values, precision limits the number of digits to be printed after decimal points.
2.45
Explanation: The format specifier %.2f ensures the floating-point number f is printed with 2 digits after the decimal point. It rounds the value if necessary.
For strings, precision limits the number of characters to be printed.
Welcome
Explanation: The format specifier %.7s prints only the first 7 characters of the string s, truncating the rest if it exceeds this length.