facebook like button

23 March, 2011

program 3: taking input from user(same previous addition program)

The code:
----------------------------------------------------------
#include<stdio.h>
main()
{
    int i,j,k;
    printf("The program to add two numbers.\n");
    printf("Enter first number.\n");
    scanf("%d",&i);
    printf("Enter second number.\n");
    scanf("%d",&j);
    k=i+j;
    printf("Sum = %d\n",k);
}
----------------------------------------------------------

     This is our first program in which we have taken input from user. So I have to explain each statement in detail to avoid any confusion(because I was very confused at that time when I was trying this). The first line inside main() is declaration of variables(same as previous program). Second line is simple printf statement. Because a good programmer always tell the user what user has to do or has to get done.The third line is also same. Now comes the fourth line (scanf statement). This statement means that your program is ready to take input from user. Observe that after scanf keyword there is a '%d' in double quotes. This '%d' tells computer that whatever input is going to be given to you(computer) will have to be taken as a decimal integer. Hence the number is scanned and assigned to 'i'.
      In the same line there is a '&' symbol before 'i'. This is the operator to get address of any variable(in our case 'i' ).  I am going to tell you the the assigning procedure in a way that may look funny but it is like this only. In the previous post I explained how declaration allocates memory to a variable. This follows that a variable has a fixed location (address) in computer memory that does not change throughout single of program. Here '&i' gives computer the address of variable i and the scanned value is filled in that address.
    Note that taking input is only related to scanf statement. It has nothing to do with the previous printf() statement. I mean if I had not written the printf() then also the program is ready to take input but it does not print any matter so you can use this program for adding purpose (because you know what your program wants) but other users who see a blank screen can not use (because they don't know what your program wants from them). I told this thing in this extra paragraph because initially I thought that printf() anf scanf() were related.
     As soon as the user enters the value of 'i'(the first value) the message for second input is printed(printf of 5th line is executed). In the exact same manner variable 'j' is scanned.
   Now rest of the program is same as the previous program for addition. you can refer to link below:
http://programsimply.blogspot.com/2011/03/program-2-addtition-of-two-numbers.html

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply