printf()
In C language, printf() is a function used to output formatted text on the console or in a file. It is declared in the standard library header file stdio.h and its syntax is:
int printf(const char *format, ...);
The first parameter format is a string literal that contains the text to be printed along with optional format specifiers. The format specifiers are placeholders for values that will be replaced during runtime, based on the type and value of additional arguments passed to the function.
For example, the %d specifier is used to print an integer, %f for a floating-point number, %c for a character, and %s for a string. There are also additional specifiers that control the width, precision, and alignment of the printed value.
Here's an example of how to use printf() to print a formatted string:
#include <stdio.h>
int main() {
int age = 25;
float weight = 68.5;
char gender = 'M';
char name[] = "John";
printf("Name: %s, Age: %d, Gender: %c, Weight: %.2f\n", name, age, gender, weight);
return 0;
}
This program will output the following text:
Name: John, Age: 25, Gender: M, Weight: 68.50
In this example, the %s specifier is used to print the name string, %d is used to print the age integer, %c is used to print the gender character, and %f is used to print the weight floating-point number with 2 decimal places.
Note that the return value of printf() is an integer that represents the number of characters printed.
format specifier
Here are some examples of format specifiers for commonly used data types:
%d: Used to format an integer value.
%f: Used to format a floating-point value.
%c: Used to format a single character.
%s: Used to format a string of characters.
%p: Used to format a pointer value.
%x: Used to format an unsigned hexadecimal value.
%o: Used to format an octal value.
%e or %E: Used to format a floating-point value in scientific notation.
%u: Used to format an unsigned decimal value.
%ld: Used to format a long integer value.
%lu: Used to format an unsigned long integer value.
Top comments (0)