Use of Scanf in C and a program to add two numbers

What is the use of scanf and how it is used ?

scanf is used to take input value from the user and store it in a variable.you will understand its use from this example.

Q. Write a program that gets two value from the user and adds them

solution:

#include<stdio.h>
#include<conio.h>
void main()
{
int num1;
int num2;
int ans;

printf("please enter the value of number 1\n");
scanf("%d",&num1);

printf("please enter the value of number 2\n");
scanf("%d",&num2);

ans=num1+num2;

printf("the answer is %d",ans);
getche();
} press ctrl+ F9 to get display


How this program works?  lets see 

1: we told that num1 ,num2 and ans are variables which will store integer constants by writing int behind them
2: first printf will diplay on screen please enter the value of number 1 and \n is called escape sequence 
3: in scanf %d tells that the type of value is integer type and &num1 means that the value entered by the user will be stored in variable num1. %d is known as format specifier
4.second printf and scanf acts same, &num2 means that the value entered by user will be stored in num2 variable.
5.ans=num1+num2 means that  both values stored in num1 and num 2 will be added and it will be stored in ans
6 in last printf() %d  will get its value which is stored in ans. and it will be displayed on screen

Variations in this program

this program can also be made like this

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
printf("enter the values of a,b\n");
scanf("%d %d",&a,&b);
c=a+b;
printf("the answer is %d",c);
getche();
}

another way to write this program is 

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
printf("enter the values of a,b\n");
scanf("%d %d",&a,&b); 

printf("the answer is %d",a+b);
getche();
}

Note:Program can be written in different styles, never copy code of anyone. Just understand the logic of program and then make it with your own mind.