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

Chapter Review

This chapter described how to write arithmetic expressions involving several operators and introduced a package of mathematical functions called Ada.Numerics.Elementary_Functions. Also introduced was the idea of an explicit type conversion. Type conversion makes it possible to mix integer and floating-point values in one expression by explicitly converting floats to integers and vice versa.

This chapter also discussed the manipulation of other scalar data types, including the standard types, Boolean and Character, and presented more detail on programmer-defined subtypes. Several new operators were introduced, including the operators REM and MOD for manipulating integers and the operators AND, OR, XOR, and NOT for manipulating Boolean data. Attention was paid to certain attributes of scalar types, such as the First and Last attributes of subtypes and the Pos and Val attributes of integer and, especially, enumeration values.

The concept of pseudorandom numbers was introduced in this chapter, along with a description of some of Ada's random-number facilities.

The CASE statement was introduced, along with a number of examples of its use. A package was shown that provided facilities for printing the value of numbers in words.

New Ada Constructs in Chapter 7

The new Ada constructs introduced in this chapter are described in Table 7.7.

Table 7.7.
Summary of New Ada Constructs

Statement			Effect

Arithmetic Assignment

I := J / K + ( L + 5) REM N;	Adds the result (an integer) of J /K to the 
				result (an integer) of (L + 5) REM N. J, K,
				L, and N must all be type Integer or an
				integer subtype. 

Character Assignment

NextCh := 'A';			Assigns the character value 'A' to NextCh.

Boolean assignment

Even := (N REM 2 = 0);		If N  is an even number,
				assigns the value True  to Even; 
				otherwise, assigns the value False  to Even.
Case Statement
CASE NextCh IS			Displays one of four messages
  WHEN 'A'|'a' =>		based on the value of NextCh  
    Ada.Text_IO.Put(Item=>"Excellent");
  WHEN 'B'|'b' =>
    Ada.Text_IO.Put(Item=>"Good");	If NextChis 'D,'d','F,'f',
  WHEN 'C'|'c'  =>			procedure Probation is
also
    Ada.Text_IO.Put(Item=>"OK");	called with IDNum  as an
  WHEN 'D'|'d'|'F'|'f' =>		actual parameter.
    Ada.Text_IO.Put(Item=>"Poor");
    Probation(WhichStudent => IDNum);
  WHEN OTHERS =>
    Ada.Text_IO.Put(Item => "Grade out of Range!");
END CASE;

Quick-Check Exercises

  1. The operator ___ means real division, the operator ___ means integer division, and the operator ___ yields the remainder of ______division.
  2. Write a Boolean condition that is True if N divides M.
  3. Evaluate the Boolean expression
    True AND ((30 REM 10) = 0)
    
  4. Evaluate the Boolean expression
    False AND (((30 REM 10) / 0) = 0)
    

    What occurs when Ada evaluates this expression? Suppose the AND were replaced by AND THEN?

  5. In the Latin-1 character set, give the values of these expressions:
    Character'Val( Character'Pos('a'))
    Character'Val( Character'Pos('a') + 3)
    Character'Val( Character'Pos('z') - 26)
    Character'Val( Character'Pos('z') - 32)
    
  6. If two variables are type compatible, can one always be assigned to the other?
  7. Under what condition can one variable be assigned to another when they are not type compatible?
  8. A CASE statement is often used instead of ___________________.
  9. Which of the following can appear in a CASE selector?

    a range of integers, a list of integers, a Float value, a Boolean value, a type Character value, a string value, an enumeration literal

Answers to Quick-Check Exercises

  1. / (float operands), / (integer operands), REM, integer
  2. ( M REM N) = 0
  3. True
  4. Constraint_Error or Numeric_Error is raised; error won't be detected because in short-circuit evaluation the right side won't be evaluated.
  5. 'a', 'd', 'a', 'Z'
  6. Yes, if they are the same type or the one getting a new value is the base type and the other is a subtype of that base type. If the one getting a new value is a subtype, the value of the variable being assigned must be in range.
  7. A variable of one numeric type can be converted to the other type.
  8. A multiple-alternative IF construct
  9. All but Float and string

Review Questions

  1. Compare and contrast integer types and floating-point types. What are the advantages and disadvantages of each?
  2. What is the result of each of the following operations?
    11 REM 2  _______    11 / 2  ________
    12 REM -3 _______    12 / -3 ________ 
    27 REM 4  _______   -25 / 4  ________ 
    18 REM 6  _______   -18 / -5 ________ 
    
    
  3. What is the result of the expression (3 + 4 / 2) + 8 - 15 REM 4?
  4. Write an assignment statement that rounds a floating-point variable Num1 to two digits after the decimal point, leaving the result in Num1.
  5. Write a procedure called Change that has one IN parameter C, type NonNegFloat, and four OUT parameters Q, D, N, and P, type Natural. The procedure returns the number of quarters in Q, the number of dimes in D, the number of nickels in N, and the number of pennies in P to make change with the minimum number of coins. C (the change amount) is less than $1.00. (Hint: Use the integer division and REM operators.)
  6. List and explain three computational errors that can occur in type Float expressions.
  7. Write an IF statement that displays True or False according to the following conditions: Either Flag is True or Color is Red, or both Money is Plenty and Time is Up.
  8. Write the statement to assign a value of True to the Boolean variable OverTime only if a worker's weekly Hours are greater than 40.
  9. Write a Boolean expression using the Character'Pos attribute that determines whether the position of 'a' in ASCII is greater than that of 'Z'. What is the value of this expression?
  10. When should an IF statement be used instead of a CASE statement?
  11. Write a CASE statement to select an operation based on Inventory. Increment TotalPaper by PaperOrder if Inventory is 'B' or 'C'; increment TotalRibbon by RibbonOrder if Inventory is 'L', 'T', or 'D'; increment TotalLabel by LabelOrder if Inventory is 'A' or 'X'. Do not take any action if Inventory is 'M'.
  12. Write the FOR statement that displays the character values of the positive numbers 32 through 126, inclusive. Use OrdNum as the loop control variable. What is the value of OrdNum after completion of the loop?

Programming Projects

  1. A company has ten employees, many of whom work overtime (more than 40 hours) each week. The company accountant wants a payroll program that reads each employee's name, hourly rate (rate), and hours worked (hours). The program must compute the gross salary and net pay as follows:
             _
            |  hours × rate ( if hours < =  40)
    gross = |
            |_ 1.5 rate ( hours - 40) + 40 × rate ( if hours > 40)
    
             _
    	|  gross ( if gross <= $65)
    net =   |
            |_ gross - ( 15 + 0.45gross) ( if gross > $65)
    

    The program should print each employee's gross salary and net pay. The total amount of the payroll, which can be computed by adding the gross salaries for all employees, should be displayed at the end. Test your program on the following data:

      
           Name         Rate   Hours
    Ivory Hunter        6.50    35     
    Track Star          4.50    10     
    Smokey Bear         3.25    80     
    Oscar Grouch        6.00    10           
    Jane Jezebel        4.65    25      
    Fat Eddie           8.00    40
    Pumpkin Pie         9.65    35
    Sara Lee            5.00    40     
    Human Eraser        6.25    52
    
    
  2. Write a program to read in a collection of integers and determine whether each is a prime number. Test your program with the four integers 7, 17, 35, and 96. All numbers should be processed in one run.
  3. Let n be a positive integer consisting of up to ten digits, d10d9...d1. Write a program to list in one column each of the digits in the number n. The right-most digit, d1, should be listed at the top of the column. (Hint: As computed according to the formula
    digit = n REM 10
    

    what is the value of digit if n = 3704?)

    Test your program for values of n equal to 6, 3704, and 170498.

  4. An integer N is divisible by 9 if the sum of its digits is divisible by 9. Use the algorithm developed for Programming Project 3 to determine whether the following numbers are divisible by 9.
    N =  154368 
    N =  621594 
    N =  123456 
    
    
  5. Redo Programming Project 4 by reading each digit of the number to be tested into the character variable Digit. Form the sum of the numeric values of the digits. (Hint: The numeric value of Digit (type Character) is
     Character'Pos( Digit) - Character'Pos('0').)
    
  6. The interest paid on a savings account is compounded daily. This means that if you start with StartBal dollars in the bank, at the end of the first day you will have a balance of
    StartBal × (1 + rate/365) 
    
    dollars, where rate is the annual interest rate (0.10 if the annual rate is 10 percent). At the end of the second day, you will have
    StartBal × (1 + rate/365) × (1 + rate/365) 
    
    dollars, and at the end of N days you will have
    StartBal × (1 + rate/365)N
    
    dollars. Write a program that processes a set of data records, each of which contains values for StartBal, rate, and N and computes the final account balance.
  7. Compute the monthly payment and the total payment for a bank loan, given:

    a. the amount of the loan,

    b. the duration of the loan in months, and

    c. the interest rate for the loan.

    Your program should read in one loan at a time, perform the required computation, and print the values of the monthly payment and the total payment. Test your program with at least the following data (and more if you want):

             Loan     Months    Rate
            16000       300    12.50    
            24000       360    13.50    
            30000       300    15.50    
            42000       360    14.50    
            22000       300    15.50    
           300000       240    15.25   
    
    (Hints: The formula for computing monthly payment is
    		   ratem × expmmonths x loan
          monthpay =  --------------------------
    			expm - 1.0
    
    where
    	ratem =  rate / 1200.0
    	expm  =  (1.0 + ratem)
    
    You will need a loop to multiply expm by itself months times. The formula for computing the total payment is
    	total = monthpay × months.)
    
    
  8. Now that you understand the body of the spider package, you can try modifying it. Here are some possibilities:

    a. Move the declaration of ScreenColors to the specification and add a function IsColor to the package that returns the spider's current color. This gives a spider program the ability to choose a new color based on the current one. Now add a procedure NextColor to Spider.MyStuff, using IsColor to determine the current color and then choosing the next one accordingly. Finally, change Draw_Box so that it draws each side of the box in a different color, using NextColor to change color.

    b. Move the spider's room-coordinate declarations (Cols, Rows, etc.) to the specification, then add to the package a procedure Jump with row and column parameters. This allows a spider program to cause the spider to jump to an arbitrary location in its room. Now write a spider program that causes the spider to move to a random location.

    c. (Difficult) Modify the package and procedure Start so that a spider program can specify the size of the room using parameters to the Start procedure. This will require a great deal of thought and re-design of the package!


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

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