To write an interactive program, you obviously need a method for requesting information from the user and another for receiving the information. When a program waits for the user to type something, it is customary to provide a prompt, a cue to the user that he is expected to do some-thing, such as Insert Coin at the arcade.
The program below, a reworking of the earlier area-of-a-triangle program, includes several new things:
Please take note of the fact that the command that produces the prompt does not include the \n newline character. This causes the cursor to remain on the prompt line while the program awaits the user's response. Note also that the prompt string ends with a wordspace after the question mark so that the response does not abut the prompt.
Each scanf() call used below to get the user's response has two arguments. They are provided to the function in a comma-separated list. Double quotes are used to enclose the first argument, a string constant. The % character introduces the formatting information for how the character data read from standard input is to be converted. The second argument is the address of the variable where the data is to be stored.
#include <stdio.h> /* standard I/O header file */
void main()
{
int b; /* base */
int h; /* height */
float A; /* Area */
/* -------------------Introduction------------------ */
printf("This program calculates and prints the area of a triangle\n");
printf("after you enter its dimensions.\n");
printf("When asked to, type in a dimension and hit the ENTER key.\n");
printf("\n");
/* -------------------Inputting Data------------------*/
printf("What is the length of the triangle's base? ");
scanf("%d", &b);
printf("What is the triangle's height? ");
scanf("%d", &h);
/* -------------------Calculation------------------ */
A = b * h / 2.0;
/* -------------------Printing Results------------------ */
printf("\n");
printf("The area of a triangle with a base of %d units and\n", b);
printf("a height of %d units is %.1f square units.\n", h, A);
}