Printf

Lesson 8
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

printf() is a function in C language that is used to print formatted output to the console. It is defined in the stdio.h header file.

Here’s a basic syntax of the printf() function:

printf("format string", argument1, argument2, ...);
  • "format string" is a string that specifies how the output should be formatted.
  • argument1, argument2, … are the variables or expressions to be printed.

The printf() function returns the number of characters printed to the console.

Here are some format specifiers used in the format string:

  • %d: Integer format specifier
  • %f: Floating-point format specifier
  • %c: Character format specifier
  • %s: String format specifier
  • %p: Pointer format specifier
  • %x: Hexadecimal format specifier
  • %o: Octal format specifier Here’s an example that demonstrates the usage of printf() function:
#include <stdio.h>

int main() {
   int age = 30;
   float salary = 5000.50;
   char gender = 'M';
   char name[] = "John Doe";
   
   printf("Name: %s\n", name);
   printf("Age: %d\n", age);
   printf("Salary: $%.2f\n", salary);
   printf("Gender: %c\n", gender);
   
   return 0;
}

Output:

Name: John Doe
Age: 30
Salary: $5000.50
Gender: M

In the above example, we have used different format specifiers to print different types of data. The %.2f format specifier is used to print the floating-point number with 2 decimal places. The \n character is used to print a newline after each output.