C programming tutorial

                  PREVIOUS                                                                                   NEXT CHAPTER

 

scanf

How to take input from user.

In the last program we saw that we did addition of two numbers by assigning value to them on our own.Instead of assigning values to variable on our own we can take input from user.For this we use function scanf.It is defined under the header file stdio.h.

scanf function allow us to accept take input from standard input.

printf("enter the value of a");

scanf("%d",&a);

here scanf will take value from user and it will store it into a.If user input will be 2.Then 2 will be stored in a.You can also take multiple values from user.

scanf("%d%d",&a,&b);

Note:Dont forget to write & in front of variable inside scanf.It is often a mistake comitted by lot of people.

 

scanf example C

Let us make program to multiply two numbers and we have to take numbers to be multiplied from user.

#include<stdio.h>

main()

{

int a ,b,c;

printf("Enter two numbers to be multiplied");

scanf("%d%d",&a,&b);

c=a*b; /* In C multiplication operator is * */

printf("multiplication of %d and %d is%d",a,b,c);

}

line printf("Enter two numbers to be multiplied") will print Enter two numbers to be multiplied on screen

 

line scanf("%d%d",&a,&b) will store first input by user in variable a and second input into variable b,

 

line c=a*b will store result of a*b into c;

 

line printf("multiplication of %d and %d is%d",a,b,c) will print multiplication result

 



                  PREVIOUS                                                                                   NEXT CHAPTER