Open In App

scanf in C

In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments.

scanf Syntax

The syntax of scanf() in C is similar to the syntax of printf().



int scanf( const char *format, ... );

Here,

Example format specifiers recognized by scanf:



%d to accept input of integers.

%ld to  accept input of long integers

%lld to accept input of long long integers

%f to accept input of real number.

%c to accept input of character types.

%s to accept input of a string.

To know more about format specifiers, refer to this article – Format Specifiers in C

Example:

int var;
scanf(“%d”, &var);

The scanf will write the value input by the user into the integer variable var.

Return Value of scanf

The scanf in C returns three types of values:

Why &?

While scanning the input, scanf needs to store that input data somewhere. To store this input data, scanf needs to known the memory location of a variable. And here comes the ampersand to rescue.

Example of scanf

Below is the C program to implement scanf:




// C program to implement
// scanf
#include <stdio.h>
 
// Driver code
int main()
{
    int a, b;
   
      printf("Enter first number: ");
      scanf("%d", &a);
   
      printf("Enter second number: ");
      scanf("%d", &b);
   
      printf("A : %d \t B : %d" ,
            a , b);
   
    return 0;
}

Output

Enter first number: 5
Enter second number: 6
A : 5      B : 6

Related Article:

Article Tags :