Getting inputs from User

Most times, we require interaction from the user, and we process the inputs given by them and display the outputs. Now have a look at the following program which does the function of adding two numbers. It takes two numbers from the user, adds it and displays the output.

Code

#include<stdio.h>
main()
{
// Declaration of variables.
int iNum1,iNum2;
int iSum;

// Getting inputs from user
printf("Enter the first number : ");
scanf("%d",&iNum1);
printf("Enter the second number : ");\
scanf("%d",&iNum2);

// Process the inputs
iSum = iNum1 + iNum2;

// Display the output
printf("\nSum of %d and %d is %d",iNum1,iNum2,iSum);

getch();

}

Output
Enter the first number  : 23
Enter the second number : 12

Sum of 23 and 12 is 35
The program is straight forward, we first display the message to the user to input the first number, then the inbuilt function "scanf" will get the input from the user. The program execution pauses at this point until the user presses "Enter" key. Once the input is given, you will prompted to enter second number, and after getting the number, it will add the two numbers and displays the output.

Important thing to be noted here is the arguments passed in the Scanf function. First string parameter is used to define format specifier. It tells the compiler that it should treat the input from the user as specified in that format specifier. Format specifiers used in Scanf are similar to the one explained in this post. When I say %d in the scanf, it expects a integer. The next argument in the scanf is the variables where we need to store the data. We use scanf to store the value we enter in some memory location. So we need to pass the address of the variable as the argument. "&" operator in the scanf statement is the address of operator. &iNum1 will give the address of iNum1 variable. So the number that is got from user is stored in the address of iNum1.

Instead of using two different statements for obtaining the inputs, we can also use one single statement as shown below.

Code
      printf("Enter two numbers  : ");
scanf("%d%d",&iNum1,&iNum2);
Output
Enter two numbers  : 12 23

Sum of 12 and 23 is 35


As shown above, we need to separate the two inputs with a space/tab/new line, if we need to give the two inputs in the same scanf statement.

0 comments:

Post a Comment

 
Template designed using TrixTG