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: %fn", 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.

Printf() and Scanf() in C

Example:

int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %dn", 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.

The printf() and scanf() functions are used for input and output in C language. Both functions are inbuilt library functions, defined in stdio.h (header file).

printf() function

The printf() function is used for output. It prints the given statement to the console.

The syntax of printf() function is given below:

  1. printf(“format string”,argument_list);

The format string can be %d (integer), %c (character), %s (string), %f (float) etc.

scanf() function

The scanf() function is used for input. It reads the input data from the console.

  1. scanf(“format string”,argument_list);

Program to print cube of given number

Let’s see a simple example of c language that gets input from the user and prints the cube of the given number.

  1. #include<stdio.h>  
  2. int main(){
  3. int number;
  4. printf(“enter a number:”);
  5. scanf(“%d”,&number);
  6. printf(“cube of number is:%d “,number*number*number);
  7. return 0;
  8. }

Output

enter a number:5
cube of number is:125

The scanf(“%d”,&number) statement reads integer number from the console and stores the given value in number variable.

The printf(“cube of number is:%d “,number*number*number) statement prints the cube of number on the console.

Related Posts

Leave a Reply