Previous | Next | Table of Contents | Index | Program List | Copyright

Chapter Review

A conditional looping structure, the WHILE statement, was used to implement loops whose repetition is controlled by a condition. The WHILE statement is useful when the exact number of repetitions required is not known before the loop begins. In designing a WHILE loop, we must consider both the loop control and loop processing operations that must be performed. Separate Ada statements are needed for initializing and updating variables appearing in the loop repetition condition.

One common technique for controlling the repetition of a WHILE loop is using a special sentinel value to indicate that all required data have been processed. In this case, an input variable must appear in the loop repetition condition. This variable is initialized when the first data value is read (priming read), and it is updated at the end of the loop when the next data value is read. Loop repetition terminates when the sentinel value is read.

The use of assertions and loop invariants in loop verification and loop design was also introduced. We will use loop invariants to document the processing performed by the loop body.

This chapter also introduced the general LOOP and EXIT statements and showed how they are used in Ada to implement robust input with exception handling.

Writing procedures is an important part of programming, and this technique was also introduced in this chapter. Finally, a package providing robust numeric input operations was developed.

New Ada Constructs in Chapter 6

The new Ada statements introduced in this chapter are described in Table 6.3.

Table 6.3
Summary of New Ada Constructs

Construct                                                Effect

WHILE Statement

Sum := 0;					A series of data items is
WHILE Sum <= MaxSum LOOP			read; their sum is accumulated
	Ada.Text_IO.Put(Item=>"Next integer > "); in Sum. This process stops
	Ada.Integer_Text_IO.Get(Item=>Next);	when the accumulated sum 
	Sum := Sum + Next;			exceeds MaxSum.
END LOOP;
Procedure with Parameters
PROCEDURE A (X : IN Float;			Procedure A has two IN parameters
      Op : IN Character;			and one IN OUT parameter
      XTo3 : IN OUT Float) IS			If Op is '*',then the value
						returned is X * X * X; otherwise, 
BEGIN --A					if Op is '+', then the value
						returned is
  IF Op = '*' THEN				X + X + X; otherwise, an error
    XTo3 := X * X * X;				message is printed.  A result is
  ELSIF Op = '+' THEN				returned by assigning a new value to
    XTo3 := X + X + X;				the actual parameter (a variable)
  ELSE						that corresponds to parameter XTo3.
    Ada.Text_IO.Put(Item => "Invalid");
  END IF;

END A; 
Procedure Call Statement

A (X=>5.5, Op=>'+', XTo3=>Y);    Calls procedure A.
                                 5.5 is passed into X, 
                                 '+' is passed into Op,
                                 and the value 16.5 is stored in Y.
Exception-Handler Block
BEGIN						If Y + Z is out of range for X,
  X := Y + Z;					"Out of Range" is displayed;
  Y := A / G;					If G=0, A cannot be
EXCEPTION					divided by G and "Overflow" is
  WHEN Constraint_Error =>			displayed. Control passes to
    Ada.Text_IO.Put(Item=>"Out of Range");	the statement following END
  WHEN Numeric_Error =>
    Ada.Text_IO.Put(Item=>"Overflow");
END;

Quick-Check Exercises

  1. A WHILE loop is called a __________ loop.
  2. A WHILE loop is always used for counting. (True or False?)
  3. The priming step for a WHILE loop is what kind of statement? When is it used?
  4. The sentinel value is always the last value added to a sum being accumulated in a sentinel-controlled loop. (True or False?)
  5. It is an error if a WHILE loop body never executes. (True or False?)

Answers to Quick-Check Exercises

  1. Conditional
  2. False
  3. An input operation, used in a sentinel-controlled loop
  4. False, the sentinel should not be processed.
  5. False

Review Questions for Chapter 6

  1. Define a sentinel value.
  2. For a sentinel value to be used properly when reading in data, where should the input statements appear?
  3. Write a program called Sum to sum and display a collection of payroll amounts entered at the standard input device until a sentinel value of -1 is entered. Use a WHILE statement.
  4. Hand trace the program below given the following data:
    	4.0, 2.0, 8.0, 4.0
    	1.0, 4.0, 2.0, 1.0
    	9.0, 3.0, 3.0, 1.0
    	-22.0, 10.0, 8.0, 2.0
    
    WITH Ada.Text_IO;
    WITH Ada.Float_Text_IO;
    PROCEDURE Slope IS
    
    	Sentinel CONSTANT Float := 0.0;
    	Slope, y2, y1, x2, x1 : Float;
    
    BEGIN -- Slope
    	Ada.Text_IO.Put(Item => "Enter four real numbers > ");
    	Ada.Text_IO.New_Line;
    	Ada.Float_Text_IO.Get(Item => y2);
    	Ada.Float_Text_IO.Get(Item => y1);
    	Ada.Float_Text_IO.Get(Item => x2);
    	Ada.Float_Text_IO.Get(Item => x1);
    	Slope := (y2 - y1) / (x2 - x1);
    	WHILE Slope /= Sentinel LOOP
    		Ada.Text_IO.Put(Item => "Slope is ");
    		Ada.Float_Text_IO.Put(Item => Slope, Fore=>1, Aft=>2, Exp=>0);
    		Ada.Text_IO.New_Line;
    		Ada.Text_IO.Put(Item => "Enter four real numbers > ");
    		Ada.Text_IO.New_Line;
    		Ada.Float_Text_IO.Get(Item => y2);
    		Ada.Float_Text_IO.Get(Item => y1);
    		Ada.Float_Text_IO.Get(Item => x2);
    		Ada.Float_Text_IO.Get(Item => x1);
    		Slope := (y2 - y1) / (x2 - x1);
    	END LOOP;
    END Slope;
    
  5. Which of the statements below is incorrect?

    a. Loop invariants are used in loop verification.

    b. Loop invariants are used in loop design.

    c. A loop invariant is always an assertion.

    d. An assertion is always a loop invariant.

  6. Write a procedure called LetterGrade that has one input parameter called Grade and that will display the corresponding letter grade using a straight scale (90-100 is an A, 80-89 is a B, etc.).
  7. Explain the difference between IN parameters, OUT parameters, and IN OUT parameters.
  8. Explain the allocation of memory cells when a procedure is called.
  9. Explain the purpose of a robust input loop.

Programming Projects

  1. Write a program that will find the product of a collection of data values. Your program should terminate when a zero value is read.
  2. Write a program to read in an integer N and compute Slow = 1 + 2 + 3 + ... + N (the sum of all integers from 1 to N). Then compute Fast = (N x (N + 1)) / 2 and compare Fast and Slow. Your program should print both Fast and Slow and indicate whether or not they are equal. (You will need a loop to compute Slow.) Which computation method is preferable?
  3. Write a program to read a list of integer data items and find and print the index of the first and the last occurrences of the number 12. Your program should print index values of 0 if the number 12 is not found. The index is the sequence number of the data item 12. For example, if the eighth data item is the only 12, the index value 8 should be printed for the first and last occurrence.
  4. Write a program to read in a collection of exam scores ranging in value from 1 to 100. Your program should count and print the number of outstanding scores (90-100), the number of satisfactory scores (60-89), and the number of unsatisfactory scores (1-59). Test your program on the following data:

    63 75 72 72 78 67 80 63 75 90 89 43 59 99 82 12 100

    In addition, print each exam score and its category.

  5. Write a program to process weekly employee time cards for all employees of an organization. Each employee will have three data items indicating an identification number, the hourly wage rate, and the number of hours worked during a given week. Each employee is to be paid time and a half for all hours worked over 40. A tax amount of 3.625 percent of gross salary will be deducted. The program output should show the employee's number and net pay.
  6. Suppose you own a soft-drink distributorship that sells Coke (ID number 1), Pepsi (ID number 2), Canada Dry (ID number 3), and Dr. Pepper (ID number 4) by the case. Write a program to

    a. read in the case inventory for each brand for the start of the week;

    b. process all weekly sales and purchase records for each brand; and

    c. display the final inventory. Each transaction will consist of two data items. The first item will be the brand identification number (an integer). The second will be the amount purchased (a positive integer value) or the amount sold (a negative integer value). The weekly inventory for each brand (for the start of the week) will also consist of two items: the identification and initial inventory for that brand. For now, you may assume that you always have sufficient foresight to prevent depletion of your inventory for any brand. (Hint: Your data entry should begin with eight values representing the case inventory. These should be followed by the transaction values.)

  7. Redesign the body of Program 6.11 (Robust_Input) so that the range of the input data is checked explicitly with an IF statement instead of including a handler for Constraint_Error. Could you eliminate exception handling altogether? (Hint: How would you deal with the case of an alphabetic character being entered instead of an integer?)
  8. The square root of a number N can be approximated by repeated calculation using the formula

    NG = .5(LG + (N / LG))

    where NG stands for next guess and LG stands for last guess. Write a function that implements this process where the first parameter will be a positive float number, the second will be an initial guess of the square root, and the third will be the computed result.

    The initial guess will be the starting value of LG. The procedure will compute a value for NG using the formula above. The difference between NG and LG is checked to see whether these two guesses are almost identical. If so, the procedure is exited and NG is the square root; otherwise, the new guess (NG) becomes the last guess (LG) and the process is repeated (i.e., another value is computed for NG, the difference is checked, etc.).

    For this program the loop should be repeated until the difference is less than 0.005 (Delta). Use an initial guess of 1.0 and test the program for the numbers: 4.0, 120.5, 88.0, 36.01, 10000.0.

  9. Modify Program 6.16 so that the spider covers the four walls completely but does not visit any parts of the walls a second time. [Hint: Count the number of steps the spider takes while touring the first wall and the number of steps in touring the third (parallel) wall.]
  10. Add and test a command NECorner to Spider.My_Stuff (Programs 6.13 and 6.14) which causes the spider to move to the northeast corner of its room. Now add and test three more commands SECorner, SWCorner, and NWCorner, which cause the spider to move to the other corners.


Previous | Next | Table of Contents | Index | Program List | Copyright

Copyright © 1996 by Addison-Wesley Publishing Company, Inc.