Back to DFS's Pascal Page


Keyboard Input I

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 something, such as Insert Coin at the arcade.

The program below, a reworking of the earlier area-of-a-triangle program, includes several new things:

  1. Simple introduction and instructions for the user;
  2. Labelled separators to break up the program visually;
  3. A programming technique for getting information from the user.

Please take note of the fact that the command that produces the prompt is a write(), not a writeln(). 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.

program TriangleAreaInteractive (input, output);
   var
      b: integer; {Base}
      h: integer; {height}
      A: real; {Area}
   begin
      {-------------------Introduction------------------}
      writeln('This program calculates and prints the area of a triangle');
      writeln('after you enter its dimensions.');
      writeln('When asked to, type in a dimension and hit the ENTER key.');
      writeln;
      {-------------------Inputting Data------------------}
      write('What is the length of the triangle''s base? ');
      readln(b);
      write('What is the triangle''s height? ');
      readln(h);
      {-------------------Calculation------------------}
      A := b * h / 2;
      {-------------------Printing Results------------------}
      writeln;
      writeln('The area of a triangle with a base of ', b:0, ' units and');
      writeln('a height of ', h:0, ' units is ', A:0:1, ' square units.')
   end.

© 1998-99 DFStermole
HTMLified 27 Dec 99