Wednesday, May 19, 2010

Accepting Input

Excited at your success of solving the problem your uncle talks to the contractor about your program. The contractor sees the value of having such a program at his disposal and contacts you for the same. However, since all the clients have different size of land, and also want different sized pavements, you wish to provide user configurable length and width parameters.
This brings us to the input part of the stdio.h header file. Getting user input is similar to showing the output.
#include "stdio.h"
int main()
{
 int length;
 scanf(“%d”, &length);
 return length;
}
Running the above program will result in the computer waiting for your input. It expects an integer and be sure to type in an integer only. It will store the value you enter in the variable “length”. Since the variable is being written to (its value is being changed) we cannot just pass the variable name, but have to append an & in front of the variable. Always remember to put the & in front of the variable when using the scanf function. Here is the stub of the program you will need to complete your assignment at the contractor’s place:
#include "stdio.h"
int main()
{
 int len1, len2, width1, width2;
 int area, rate;
 printf(“Enter outside length “);
 scanf(“%d”, &len1);
 printf(“Enter outside width “);
 scanf(“%d”, &width);
 …
 area = (len1*width1)-(len2*width2);
 scanf(“%d”, &rate);
 printf(“Cost of paving = Rs.%d\n”, area*rate);
}
[Exercise] The paving company has a dedicated computer to do this calculation. They do not wish to run the program again and again after each calculation. Encompass your program with something that will cause the first question to appear soon after the cost of the first pavement is done displaying.
[Exercise] Some customers may want to check with various rates. Modify your program such that the program will remember the previous inputs. Finally the program will ask for user input in the following fashion:
Enter outside length [enter 0 for 1200] _
Previously the user had entered 1200. This time she could just enter 0 to assume the same value as previous.
This problem also teaches a lesson in usability of systems. Lack of ease of inputs is a major reason that many banks, ATMs and vending machines have long queues.
Side note: We never entered the units. This is because arithmetically units don’t matter. However when interacting with the user, it is always best to make the units clear. You may also want to write a conversion program or modify the existing one to support both US units as well as metric units.

No comments: