Dremendo Tag Line

scanf() Function and its Use in C programming

Input and Output in C

In this lesson, we will look at what is scanf() function in C programming and how it works along with some example.

What is scanf() Function

The scanf() function is used in the C program to accept input from the standard input device (keyboard) and store them in one or more variables.

The scanf() is similar to printf() function. Instead of printing data on the output device (monitor), it reads data entered from the input device (keyboard).

Let's see some examples for more understanding.

Example 1

C program to input a character and store in a character variable.

#include <stdio.h>
#include <conio.h>

int main()
{
    char a;
    printf("Enter any character ");
    scanf("%c",&a);
    printf("You have entered %c",a);
    return 0;
}

Output

Enter any character b
You have entered b

Here you can see that in line number 7 we have prompt the user to input any character from the keyboard. On line number 8 we have used scanf() function to read a character from the keyboard and store it in a character variable a.

To input a character type value, we have used %c (format specifier of char) inside the scanf() function and variable a has been used to store the character. Remember that you have to use ampersand & (address-of operator) with the variable name inside the scanf() function while taking inputs from the keyboard.

You can use any variable name you want but remember to follow the variable naming rules that we have discussed earlier. On line number 9 we have printed the value of the character variable a on the screen.

Example 2

C program to input and store an integer number, a float number and a double type number in three variables.

#include <stdio.h>
#include <conio.h>

int main()
{
    int a;
    float b;
    double c;
    printf("Enter an integer, a float and a double type numbers\n");
    scanf("%d%f%lf",&a,&b,&c);
    printf("You have entered an integer number %d, a float number %.2f and a double type number %lf",a,b,c);
    return 0;
}

Output

Enter an integer, a float and a double type numbers
18
54.2365
91.16249
You have entered an integer number 18, a float number 54.24 and a double type number 91.162490
                                

You can see that we have used %d (format specifier of int), %f (format specifier of float) and %lf (format specifier of double) inside the scanf() function to accept an integer, a float and a double type numbers from the keyboard and store in the variables a,b and c respectively.

video-poster

Test Your Knowledge

Attempt the multiple choice quiz and practical questions to check if the lesson is adequately clear to you.

Test Your Knowledge