Reading User Values

The previous program is good, but it would be better if it read in the values 5 and 7 from keyboard that is typed by the user instead of using constants. This is the program:


#include <stdio.h>

int main()
{
    int d,e,f;
    printf("Enter the first value:");
    scanf("%d", &d);
    printf("Enter the second value:");
    scanf("%d", &e);
    f=d+e;
    printf("%d + %d = %d\n", d,e,f);
    getchar();
    getchar();
    return 0;

}
Just by using command ‘scanf’ the Processor immediately read typed character from the keyboard. The character typed will be stored in variable d and e. & is the address operator in C: It returns the address of the variable. You must use the & operator in scanf on any variable of type char, int, or float. If you leave out the & operator, there is no error when you compile the program but you will get an error when you run the program.

There error as shown above is 4 + 5 = 4206601. This is due to missing & operator for variable d.

Next Page >>
<< Back to Electronics