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.


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.


#include <stdio.h>

int main()
    int num;
    printf("Enter any number : ");
    scanf("%d", &num);
    printf("Number = %d", num);
    return 0;
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()

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

Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< pre>< code >----Your Source Code---- < / code > < / pre > (Remove spaces from pre and code tags)

No comments:

Post a Comment