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

Chapter Review

Multidimensional arrays were used to represent tables of information and game boards. Nested loops are needed to manipulate the elements of a mutidimensional array in a systematic way. The correspondence between the loop-control variables and the array subscripts determines the order in which the array elements are processed.

Also in this chapter, we introduced variant records. A variant record is one that can have one of several structures, depending on the value of a special field called the discriminant. We used variant records to represent employee records and geometric figures.

New Ada Constructs in Chapter 12

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

Table 12.1 Summary of New Ada Constructs

Construct					Effect

Declaring Multidimensional Arrays

SUBTYPE Weeks IS Positive RANGE 1..52;		YearMatrix describes a two-
TYPE Days IS					dimensional array with  
  ( Mon,Tue,Wed,Thu,Fri,Sat,Sun);		52 rows and 7 columns
						(days of the week).

TYPE YearMatrix IS 
  ARRAY( Weeks,Days) OF Float;			Sales is an array of 
						this type and can
Sales : YearMatrix;				store 364 float numbers.  

Multidimensional Array References

Sales := ( OTHERS=>( OTHERS=>0.0));		Initializes all elements 
						of Sales to zero.

Ada.Float_Text_IO.Put(Item=>Sales(3, Mon));	Displays the element of
						Sales for Monday of week 3.

Ada.Float_Text_IO.Get(Item=>Sales(1, Sun));	Reads the value for the 
						first Sunday into Sales.


TotalSales := 0.0;				Finds the total sales for
FOR Week IN Weeks LOOP				the entire year.
  FOR Today IN Days LOOP
    TotalSales := TotalSales + Sales( Week,Today);
  END LOOP;
END LOOP;

Variant Record Declaration

						A record type with a 
TYPE KidKind IS ( Girl, Boy);			variant part is declared.
						The discriminant is an 
TYPE Child( Sex: KidKind:=Girl) IS RECORD	enumeration value.
  First: Character;				Each record variable 
  Last: Character;				can store two
  Age: Natural;					characters and an integer.
						One variant part can
  CASE Sex IS					store two float values, 
    WHEN Girl =>				and the other can store
      Sugar: Float;				three integer values.
      Spice: Float;
    WHEN Boy =>
      Snakes: Integer;
      Snails: Integer;
      Tails: Integer;
  END CASE;

END RECORD;	

Kid : Child;					Kid is a Child record.

Referencing a Record Variant

						Uses a CASE statement to
CASE Kid.Sex IS					read data into the variant 
  WHEN Girl =>					part of the record Kid.
    Ada.Text_IO.Put(Item => "Lbs. of sugar>");
    Ada.Float_Text_IO.Get
      (Item=>Kid.Sugar);			If discriminant is Girl,
  WHEN Boy =>					reads a value into the
    Ada.Integer_Text_IO.Put
      (Item=>"No. of snakes>");			field Kid.Sugar; if the
    Ada.Integer_Text_IO.Get(Item=>Kid.Snakes);	discriminant is Boy, reads
END CASE;					a value into the field 
						Kid.Snakes.

Quick-Check Exercises

  1. How many subscripts can an array have in Ada?
  2. What is the difference between row-major and column-major order? Which does Ada use?
  3. What does row-major order mean when an array has more than two subscripts?
  4. What control structure is used to process all the elements in a multidimensional array?
  5. Write a program segment to display the sum of the values (type Float) in each column of a two-dimensional array, Table, with data type ARRAY (1..5, 1..3) OF Float. How many column sums will be displayed? How many elements are included in each sum?
  6. Write the type declaration for an array that stores the batting averages by position (Catcher, Pitcher, FirstBase, and so on) for each of 15 baseball teams in each of two leagues (American and National).
  7. When should you use a variant record?
  8. Explain the use of the discriminant field. Can a variant record have more than one discriminant field?
  9. Explain the difference between a constrained variant record and an unconstrained one.

Answers to Quick-Check Exercises

  1. There is no specific limit; however, the size of the array is limited by the memory space available, and multidimensional arrays require memory equal to the product of the dimensions, which can be quite large.
  2. In row-major order the first row of the array is placed at the beginning of the memory area allocated to the array. It is followed by the second row, and so on. In column-major order, the first column is placed at the beginning of the array memory area. The Ada standard does not specify an ordering, but many compilers use row-major order.
  3. If an array Table has N subscripts, the array elements are placed in memory in the order Table(1,1,...,1,1), Table(1,1,...,1,2), Table(1,1,...,1,3), and so on. Then the next-to-last subscript is changed and the elements Table(1,1,...,2,1), Table(1,1,...,2,2), Table(1,1,...,2,3) ... are placed. The first subscript will be the last one that changes.
  4. Nested FOR loops
  5.     ColumnSum := 0.0;
        FOR Column IN 1..3 LOOP
          ColumnSum := 0.0;
          FOR Row IN 1..5 LOOP
            ColumnSum := ColumnSum + Table(Row,Col);
          END LOOP;
          Ada.Text_IO.Put(Item=>"Sum for column ");
          Ada.Integer_Text_IO.Put(Item=>Column, Width=>1);
          Ada.Text_IO.Put(Item=>"is ");
          Ada.Integer_Text_IO.Put(Item=>ColumnSum);
        END LOOP;
    

    Three column sums, five elements added per column.

  6.     TYPE Position IS (Pitcher, Catcher, FirstBase, SecondBase,ThirdBase,
          ShortStop, LeftField, CenterField, RightField);
        TYPE League IS (American, National);
        SUBTYPE Teams IS Positive RANGE 1..15;
        TYPE BAArray IS ARRAY (League, Teams, Position) OF Float;
    
  7. When an object has some fields that are always the same and a small number of fields that may be different.
  8. The discriminant field is a special field of a variant record, used to distinguish between the variants. A record may have more than one discriminant.
  9. A constrained variant record is one in which the discriminant is given a value when the variable is declared, which "locks in" the variant. An unconstrained record is one in which a default value was supplied for the discriminant. In an unconstrained record variable, the variant can change over the life of the variable.

Review Questions for Chapter 12

  1. Define row-major order and column-major order. For an array type whose three dimensions are (1..4), (2..3), and (5..7), draw storage layouts for both row-major and column-major order.
  2. Write the variant declaration for Supplies, which consists of either Paper, Ribbon, or Labels. For Paper, the information needed is the number of sheets per box and the size of the paper. For Ribbon, the size, color, and kind (Carbon or Cloth) are needed. For Labels, the size and number per box are needed. For each supply, the cost, number on hand, and reorder point must also be stored. Use whatever data types are appropriate for each field.
  3. Write the declaration for Vehicle. If the vehicle is a Truck, then BedSize and CabSize are needed. If the vehicle is a Wagon, the third seat or not is needed (Boolean). If the vehicle is a Sedan, the information needed is TwoDoor or FourDoor. For all vehicles, we need to know whether the transmission is Manual or Automatic; if it has AirConditioning, PowerSteering, or PowerBrakes (all Boolean); and the gas mileage. Use whatever data types are appropriate for each field.

Programming Projects

  1. Starting with the tic-tac-toe procedures from Section 12.1, develop an interactive program that allows two persons to play tic-tac-toe against each other.
  2. Starting with the class-enrollment program segments in Section 12.2, develop an interactive program for the registrar to use.
  3. Write a set of procedures to manipulate a pair of matrices. You should provide procedures for addition, subtraction, and multiplication. Each procedure should validate its input parameters (i.e., check all matrix dimensions) before performing the required data manipulation.
  4. The results from the mayor's election have been reported by each voting precinct as follows:
    	     Candidate	     Candidate	     Candidate	     Candidate
     Precinct	 A		 B		 C		 D
        1		192		48		206		37
        2		147		90		312		21
        3		186		12		121		38
        4		114		21		408		39
        5		267		13		382		29
    

    Write a program to do the following:

    a. Display the table with appropriate headings for the rows and columns.

    b. Compute and display the total number of votes received by each candidate and the percent of the total votes cast.

    c. If any one candidate received over 50% of the votes, the program should print a message declaring that candidate the winner.

    d. If no candidate received 50% of the votes, the program should print a message declaring a run-off between the two candidates receiving the highest number of votes; the two candidates should be identified by their letter names.

    e. Run the program once with the above data and once with candidate C receiving only 108 votes in precinct 4.

  5. Write a program that reads the five cards representing a poker hand into a two-dimensional array (first dimension, suit; second dimension, rank). Evaluate the poker hand by using procedures to determine whether the hand is a flush (all one suit), a straight (five consecutive cards), a straight flush (five consecutive cards of one suit), four of a kind, a full house (three of one kind, two of another), three of a kind, two pair, or one pair.
  6. Do Problem 5, but represent a card as a record with two fields representing the suit and the rank, and a poker hand as an array of these records.
  7. Modify the package Spiders ( Program 10.19) as suggested in Section 12.3, to detect spider collisions in the room. Modify the program Draw_Many_Boxes ( Program 10.20) so that something useful is done when a collision is detcted.
  8. Modify the employees and data base packages ( Program 10.11 through Program 10.18) to accommodate the variant record


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

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