Printf() and Scanf() in C


 


Printf() and Scanf() in C

Printf()

The printf() function is used to format and print output to the console. It takes a format string and a variable number of arguments, which are substituted into the format string.


Syntax:


printf(format_string, arg1, arg2, ...);
  • format_string: A string containing format specifiers.
  • arg1, arg2, ...: Optional arguments to be substituted into the format string.

Example:


int age = 25;
float pi = 3.14159;
char name[] = "Alice";

printf("My name is %s and I am %d years old.\n", name, age);
printf("The value of pi is: %f\n", pi);

Scanf()

The scanf() function is used to read formatted input from the console. It takes a format string and a variable number of pointers to variables where the input will be stored.


Syntax:


scanf(format_string, &arg1, &arg2, ...);

  • format_string: A string containing format specifiers.
  • &arg1, &arg2, ...: Pointers to variables where the input will be stored.

Example:


int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %d\n", number);

Key Points:

  • printf() is used to print output to the console.
  • scanf() is used to read input from the console.
  • Format specifiers control how data is printed or read.
  • The & operator is used to pass the address of a variable to scanf().
  • Always check the return value of scanf() to ensure successful input.

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!