Taking input from user using scanf() function

We use scanf() function in C to take formatted input from user. It is defined in stdio.h header file. Here we will see how to take simple inputs from scanf() function.

Syntax:

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

How to Use:

scanf("format-specifier", &variable-name);
Here format-specifier denotes the format specifier of input. And variable-name specifies the name of variable in which input is to be taken. The variable name is prefixed by &(Address of operator) which returns the address of the variable. If & is somewhat confusing you leave it we will see in-depth use of & later in pointers. Lets see basic input program.

Program:

#include <stdio.h>

int main()
{
    int num;
    
    printf("Enter any number : ");
    scanf("%d", &num);
    
    printf("Number = %d", num);
    
    return 0;
}
Output:
Enter any number : 120
Number = 120

Taking multiple inputs:

#include <stdio.h>

int main()
{
    int num1, num2,num3;
    float f1, f2;
    printf("Enter two number:\n");

    //Multiple scanf() can be used to take multiple inputs.
    scanf("%d", &num1);
    scanf("%d", &num2);

    printf("Enter a number and two float values:\n");

    //All inputs can also be taken in a single scanf()
    scanf("%d%f%f",&num3,&f1,&f2);

    printf("Num1 = %d, Num2 = %d, Num3 = %d\n", num1,num2,num3);
    printf("f1 = %f, f2 = %f\n",f1,f2);
    return 0;
}
Output:
Enter two number:
12
10
Enter a number and two float values:
130
1.2
1.6
Num1 = 12, Num2 = 10, Num3 = 130
f1 = 1.200000, f2 = 1.600000


Labels: ,