Skip to main content

Printf Function

The printf Function

  • The printf function is a standard library function in C that is used to format and print data to the standard output stream (usually the console or terminal).

  • It allows you to display formatted text and values by specifying format specifiers that indicate the type and formatting of the data.

The general syntax of the printf function is:

int printf(const char* format, ...);
  • The printf function takes a format string as its first argument, which is a string literal or a character array containing the text and format specifiers.

  • The format specifiers are denoted by % followed by a character that indicates the type of the value to be printed.

Here are some commonly used format specifiers:

  • %d or %i: Integer (decimal).
  • %f: Floating-point number.
  • %c: Character.
  • %s: String.
  • %p: Pointer.
  • %x or %X: Integer (hexadecimal).

Example

#include <stdio.h>

int main() {
int age = 25;
float height = 1.75;
char grade = 'A';
char name[] = "John";

printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("Height: %.2f\n", height);
printf("Grade: %c\n", grade);

return 0;
}

Explanation:

  • The printf function is used to display the name, age, height, and grade of a person.
  • The format specifiers %s, %d, %.2f, and %c are used to specify the expected types of the values to be printed.

Output

Name: John
Age: 25
Height: 1.75
Grade: A
return value

Note that the printf function returns the number of characters printed, excluding the null-terminating character. If an error occurs during printing, a negative value is returned.