Sunteți pe pagina 1din 42

CHAPTER 2

DATA TYPES

ADE

TYPE is a set of values and operations that are possible on the values.

CLASSIFICATION OF TYPES:

Ada Types

Elementary Types

Composite Types

Access

Scalar

Array

Record

Tagged

Private

Protected Task

Discrete

Real

Enumeration

Integer

Float

Fixed

Character Boolean

User- Modular Defined

Signed

Ordinary

Decimal

ADE

Integer Data Type represents whole numbers General form of declaration is : list of data names : INTEGER; where the list of data names are made up of Ada legal names separated by commas Example: A : INTEGER; FIRST, SECOND, THIRD : INTEGER; DOZEN : constant INTEGER := 12; Arithmetic Operations
+ * / ** mod rem abs for addition for subtraction / negation for multiplication for division for exponentiation for modulo arithmetic for remainder absolute value

Relational Operations
= < > <= >= for equality for less than for greater than for less than or equal to for greater than or equal to

Other operations
INTEGER'FIRST INTEGER'LAST INTEGER'SUCC INTEGER'PRED INTEGERIMAGE INTEGERVALUE

ADE

-- A sample program to demonstrate integer arithmetic operations with TEXT_IO; package INTEGER_IO is new TEXT_IO.INTEGER_IO (INTEGER); with TEXT_IO, INTEGER_IO; use TEXT_IO, INTEGER_IO; procedure INTEGER_OPERATIONS is FIRST_NUMBER, SECOND_NUMBER : INTEGER; RESULT : INTEGER := 0; -- A program to demonstrate integer arithmetic operations begin PUT_LINE("INTEGER_OPERATIONS program has started to execute.."); FIRST_NUMBER := 3; -- assign 3 to FIRST_NUMBER SECOND_NUMBER := 2; -- assign 2 to SECOND_NUMBER RESULT := FIRST_NUMBER + SECOND_NUMBER; -- integer addition NEW_LINE; PUT("3 + 2 = "); PUT(RESULT); RESULT := FIRST_NUMBER - SECOND_NUMBER; -- integer subtraction NEW_LINE; PUT("3 - 2 = "); PUT(RESULT); RESULT := FIRST_NUMBER * SECOND_NUMBER; -- integer multiplication NEW_LINE; PUT("3 * 2 = "); PUT(RESULT); RESULT := FIRST_NUMBER / SECOND_NUMBER; -- integer division NEW_LINE; PUT("3 / 2 = "); PUT(RESULT); RESULT := - FIRST_NUMBER; -- integer negation NEW_LINE; PUT(" -3 = "); PUT(RESULT); RESULT := FIRST_NUMBER ** SECOND_NUMBER; -- integer exponentiation NEW_LINE; PUT("3 ** 2 = "); PUT(RESULT); RESULT := FIRST_NUMBER rem SECOND_NUMBER; -- integer remainder NEW_LINE; PUT("3 remainder 2 = "); PUT(RESULT); RESULT := FIRST_NUMBER mod SECOND_NUMBER; -- integer modulo NEW_LINE; PUT("3 modulo 2 = "); PUT(RESULT); end INTEGER_OPERATIONS;
ADE

Character Data Type represents individual characters - 256 characters in the ISO-8 bit8859-1 character set nul, 1, 9, A, Z, a, ..z,..] General form of declaration is : list of data names : CHARACTER; where the list of data names are made up of Ada legal names separated by commas Example: KEY : CHARACTER; FIRST_CHARACTER, SECOND_CHARACTER: CHARACTER; SINGLE_QUOTE : constant CHARACTER := ; Some Attributes CHARACTER'SUCC CHARACTER'PRED CHARACTER'POS CHARACTER'VAL Relational Operations = for equality < for less than > for greater than <= for less than or equal to >= for greater than or equal to

ADE

-- A sample program to demonstrate character operations

with TEXT_IO; package INTEGER_IO is new TEXT_IO.INTEGER_IO (INTEGER); with TEXT_IO, INTEGER_IO; use TEXT_IO, INTEGER_IO; procedure CHARACTER_OPERATIONS is FIRST_CHARACTER, RESULT_CHARACTER : CHARACTER; RESULT_INTEGER : INTEGER; -- A program to demonstrate character operations begin PUT_LINE("CHARACTER_OPERATIONS program has started to execute.."); FIRST_CHARACTER := 'C'; -- assign C to FIRST_CHARACTER
RESULT_CHARACTER := CHARACTER'SUCC (FIRST_CHARACTER) ; -- Successor operation

NEW_LINE; PUT("Successor of 'C' is "); PUT(RESULT_CHARACTER); RESULT_CHARACTER := CHARACTER'PRED (FIRST_CHARACTER) ; -- Predecessor operation NEW_LINE; PUT("Predecessor of 'C' is "); PUT(RESULT_CHARACTER); RESULT_INTEGER := CHARACTER'POS (FIRST_CHARACTER) ; -- Char position operation NEW_LINE; PUT("Position of 'C' is "); PUT(RESULT_INTEGER); RESULT_CHARACTER := CHARACTER'VAL (RESULT_INTEGER) ; -- Char value operation NEW_LINE; PUT("Character value of 'C' is "); PUT(RESULT_CHARACTER); end CHARACTER_OPERATIONS;

ADE

Boolean Data Type Represents TRUE or FALSE General form of declaration is : list of data names : BOOLEAN; where the list of data names are made up of Ada legal names separated by commas Example: FIRST_RESULT, SECOND_RESULT : BOOLEAN; T : constant BOOLEAN := TRUE; Logical Operations
and or not xor and then or else

Relational Operations
= < > <= >= for equality for less than for greater than for less than or equal to for greater than or equal to

ADE

-- A sample program to demonstrate boolean operations with TEXT_IO; package BOOLEAN_IO is new TEXT_IO.ENUMERATION_IO (BOOLEAN); with TEXT_IO, BOOLEAN_IO; use TEXT_IO, BOOLEAN_IO; procedure BOOLEAN_OPERATIONS is FIRST_NUMBER, SECOND_NUMBER : INTEGER; FIRST_CHARACTER, SECOND_CHARACTER : CHARACTER; FIRST_RESULT, SECOND_RESULT, RESULT : BOOLEAN; -- A program to demonstrate boolean operations begin PUT_LINE("BOOLEAN_OPERATIONS program has started to execute.."); FIRST_NUMBER := 3; -- assign 3 to FIRST_NUMBER SECOND_NUMBER := 5; -- assign 5 to SECOND_NUMBER FIRST_CHARACTER := 'B'; -- assign B to FIRST_CHARACTER SECOND_CHARACTER := 'C'; -- assign C to SECOND_CHARACTER FIRST_RESULT := FIRST_NUMBER = SECOND_NUMBER; -- compare for equality NEW_LINE; PUT("3 = 5 ? "); PUT(FIRST_RESULT); SECOND_RESULT := FIRST_CHARACTER = SECOND_CHARACTER; NEW_LINE; PUT("'B' = 'C' ? "); PUT(SECOND_RESULT); -- combine operations RESULT := FIRST_RESULT OR SECOND_RESULT; NEW_LINE; PUT ("3 = 5 OR 'B' = 'C' ? "); PUT(RESULT);

end BOOLEAN_OPERATIONS;

ADE

Float Data Type Represents approximations of real numbers General form of declaration is : list of data names : FLOAT; where the list of data names are made up of Ada legal names separated by commas Example: FIRST_REAL, SECOND_REAL : FLOAT; PI : constant FLOAT := 3.1415927; Arithmetic Operations
+ * / ** abs for addition for subtraction / for negation for multiplication for division for exponentiation absolute value

Relational Operations
= < > <= >= for equality ( Do not use) for less than for greater than for less than or equal to for greater than or equal to

Other operations
FLOAT'DIGITS FLOATFIRST FLOATLAST FLOATPRED FLOATSUCC FLOATIMAGE FLOATVALUE

ADE

-- A sample program to demonstrate float operations with TEXT_IO; package FLOAT_IO is new TEXT_IO.FLOAT_IO (FLOAT); with TEXT_IO, FLOAT_IO; use TEXT_IO, FLOAT_IO; procedure FLOAT_OPERATIONS is FIRST_NUMBER, SECOND_NUMBER, RESULT : FLOAT; -- A program to demonstrate float operations begin PUT_LINE("FLOAT_OPERATIONS program has started to execute.."); FIRST_NUMBER := 3.5; SECOND_NUMBER := 2.6; -- assign 3.5 to FIRST_NUMBER --assign 2.6 to SECOND_NUMBER

RESULT := FIRST_NUMBER + SECOND_NUMBER; -- float addition NEW_LINE; PUT("3.5 + 2.6 = "); PUT(RESULT); RESULT := FIRST_NUMBER - SECOND_NUMBER; -- float subtraction NEW_LINE; PUT("3.5 - 2.6 = "); PUT(RESULT); RESULT := FIRST_NUMBER * SECOND_NUMBER; -- float multiplication NEW_LINE; PUT("3.5 * 2.6 = "); PUT(RESULT); RESULT := FIRST_NUMBER / SECOND_NUMBER; -- float division NEW_LINE; PUT("3.5 / 2.6 = "); PUT(RESULT); RESULT := - FIRST_NUMBER; -- float negation NEW_LINE; PUT(" -3.5 = "); PUT(RESULT); RESULT := FIRST_NUMBER ** 2; -- float exponentiation NEW_LINE; PUT("3.5 ** 2 = "); PUT(RESULT); end FLOAT_OPERATIONS;

ADE

10

-- Sample program to demonstrate attributes of scalar types with TEXT_IO; package FLOAT_IO is new TEXT_IO.FLOAT_IO (FLOAT); package BOOL_IO is new TEXT_IO.ENUMERATION_IO (BOOLEAN); package INT_IO is new TEXT_IO.INTEGER_IO (INTEGER); with TEXT_IO, INT_IO, FLOAT_IO, BOOL_IO; use TEXT_IO, INT_IO, FLOAT_IO, BOOL_IO; procedure ATTRIBUTES is DOZEN : constant INTEGER := 12; PI : constant FLOAT := 3.14159; begin -- attributes PUT (" INTEGER'FIRST = "); PUT (INTEGER'FIRST); NEW_LINE; PUT (" INTEGER'LAST = "); PUT (INTEGER'LAST); NEW_LINE; PUT (" FLOAT'FIRST = "); PUT (FLOAT'FIRST); NEW_LINE; PUT (" FLOAT'LAST = "); PUT (FLOAT'LAST); NEW_LINE; PUT (" BOOLEAN'FIRST = "); PUT (BOOLEAN'FIRST); NEW_LINE; PUT (" BOOLEAN'LAST = "); PUT (BOOLEAN'LAST); NEW_LINE; PUT (" INTEGER'PRED(0) = "); PUT (INTEGER'PRED(0)); NEW_LINE; PUT (" INTEGER'SUCC(DOZEN) = "); PUT (INTEGER'SUCC(DOZEN)); NEW_LINE;
ADE

--

outputs the smallest integer

--

outputs the largest integer

--

outputs the smallest float value

--

outputs the largest float value

--

outputs FALSE

--

outputs TRUE

--

outputs -1

--

outputs 13

11

PUT (" FLOAT'PRED(1.0) = "); PUT (FLOAT'PRED(1.0)); NEW_LINE; PUT (" FLOAT'SUCC(1.0) = "); PUT (FLOAT'SUCC(1.0)); NEW_LINE; PUT (" BOOLEAN'IMAGE(false)) = "); PUT (BOOLEAN'IMAGE(false)); NEW_LINE; PUT (" INTEGER'IMAGE(-31)) = "); PUT (INTEGER'IMAGE(-31)); NEW_LINE; PUT (" INTEGER'VALUE(""31"") = "); PUT (INTEGER'VALUE("31")); NEW_LINE;

-- outputs the machine value immediately -- preceding 1.0 -- outputs the machine value immediately -- following 1.0

-- outputs FALSE the string

-- outputs "-31" the string

-- outputs 31 the integer

PUT (" BOOLEAN'VALUE(""FALSE"") = "); PUT (BOOLEAN'VALUE("FALSE")); NEW_LINE; end ATTRIBUTES;

-- outputs FALSE

ADE

12

Constants are values in a program that remain constant throughout the program.

General form of Numeric constant declaration is data name : constant := value; Examples are : SPEED_OF_LIGHT : constant := 3.0E10; -- speed in cm/sec RADIUS_OF_EARTH : constant := 6.37E6; -- radius in meters PENNIES_PER_DOLLAR : constant := 100; TWO_PI : constant := 2*3.14159; -- two pi DIAMETER_OF_EARTH : constant := 2 * RADIUS_OF_EARTH;

General form of Non-Numeric constant declaration is data name : constant data type := value; Examples are : ABSOLUTE_TRUTH : constant BOOLEAN := TRUE; CARRIAGE_RETURN : constant CHARACTER := ASCII.CR;

ADE

13

Expressions

Strong typing Precedence of arithmetic operations exponentiation multiplication or division negation addition or subtraction Example : -3 + 2 * 3 ** 2 = (-3) + (2 * (3**2)) Use of parentheses to control order of evaluation Example : (5 - 3) * 2 = 4 CHARACTER'SUCC ( CHARACTER'SUCC ('C)) = E Order of operations among different classes of operations Arithmetic operations Relational operations Boolean operations (Except 'not' which has the same precedence as negation)

ADE

14

-- A sample program to demonstrate the use of expressions with TEXT_IO; package FLOAT_IO is new TEXT_IO.FLOAT_IO (FLOAT); with TEXT_IO, FLOAT_IO; use TEXT_IO, FLOAT_IO; procedure DISTANCE_POINTS is FIRST_X, FIRST_Y : FLOAT; SECOND_X, SECOND_Y : FLOAT; DISTANCE : FLOAT; -- A program to calculate the square of distance between two -- points in a map given their coordinates begin PUT_LINE("DISTANCE_POINTS program has started to execute.."); PUT_LINE (" Input the first x coordinate "); GET (FIRST_X); NEW_LINE; PUT (FIRST_X); NEW_LINE; PUT_LINE (" Input the first y coordinate "); GET (FIRST_Y); NEW_LINE; PUT (FIRST_Y); NEW_LINE; PUT_LINE (" Input the second x coordinate "); GET (SECOND_X); NEW_LINE; PUT (SECOND_X); NEW_LINE; PUT_LINE (" Input the second y coordinate "); GET (SECOND_y); NEW_LINE; PUT (SECOND_y); NEW_LINE; DISTANCE := (SECOND_X - FIRST_X) ** 2 + (SECOND_Y - FIRST_Y) ** 2; PUT (" Square of the distance is "); PUT ( DISTANCE); end DISTANCE_POINTS;
ADE

15

Control Structures provide alternative paths through the code.

The three kinds of control structures in Ada:

- Conditional control structure - If statement - Case statement

- Loop control structure

- Unconditional control structure

ADE

16

If statement General form : 1. if Boolean expression then statements end if; if Boolean expression then statements else statements end if; if Boolean expression then statements elsif Boolean expression then statements elsif Boolean expression then statements . . . else statements end if;

2.

3.

ADE

17

-- A sample program to demonstrate the use of 'if' statments

with TEXT_IO; package FLOAT_IO is new TEXT_IO.FLOAT_IO (FLOAT); with TEXT_IO; use TEXT_IO; with FLOAT_IO; use FLOAT_IO; procedure GREETING is -- Present a greeting depending on the time of day TIME_OF_DAY : FLOAT; begin PUT_LINE (" The greeting program has started to execute .."); PUT ("Enter the time of day in terms of a 24 hour clock "); NEW_LINE; GET(TIME_OF_DAY); NEW_LINE; PUT (TIME_OF_DAY); NEW_LINE; if TIME_OF_DAY >= 0.0 and TIME_OF_DAY <=6.0 then PUT_LINE (" It's too early ! "); elsif TIME_OF_DAY > 6.0 and TIME_OF_DAY <=12.0 then PUT_LINE (" Good morning "); elsif TIME_OF_DAY > 12.0 and TIME_OF_DAY <=18.0 then PUT_LINE (" Good afternoon "); elsif TIME_OF_DAY > 18.0 and TIME_OF_DAY <=24.0 then PUT_LINE (" Good evening "); else PUT_LINE (" Invalid time typed in "); end if; end GREETING;
ADE

18

CASE Statement multiway test. Program must decide whether the test expression takes on one of the possible values for the variable. General form : case discrete data name is when discrete data values => statements when discrete data values => statements when discrete data values => statements . . when discrete data values => statements end case; Rules that apply to the case statements 1. The case expression must be of a discrete type 2. Every possible value of the case expression must be covered in one and only one when clause 3. If the when others clause is used, it must appear as a single choice at the end of the case statement 4. Choices in a when clause must be static Example : case RESPONSE is when 'a'..'z'| 'A'..'Z' => PUT_LINE (" letter "); when '0'..'9' => PUT_LINE ("digit "); when others => PUT_LINE ("special or control character"); end case;

ADE

19

Loop Control designated to introduce repetition in a program

There are 3 basic forms of the loop statement

- the simple loop statement for infinite loops - the for loop statement for finite loops - the while loop statement for logically controlled loops

ADE

20

Simple or Infinite loop repeats the statements contained in the loop statement forever

General form : loop statements end loop;

Normal way of exiting a loop statement is exit when Boolean expression;

Example : 1. loop PUT_LINE (Help ! I cant stop ! ); end loop;

2.

loop -- executable statements if A = 0 then exit; end if; -- executable statements end loop;

3.

loop -- executable statements exit when A =0; - executable statements

end loop;

ADE

21

For loops you can specify how many times to execute the loop

General forms :

for loop parameter in first value .. last value loop statements end loop;

Rules that apply to for loops 1. The loop counter is not explicitly declared 2. The loop counters range is tested at the beginning of the loop, not at the end of the loop 3. Inside the loop, the loop counter may be used but not altered 4. The loop counters discrete range may be dynamic 5. The discrete range of the loop is evaluated before the for loop is first executed 6. The loop counter only exists within the loop 7. For loops may only loop over a discrete range 8. For loops may step through the discrete range in reverse order

ADE

22

-- Sample program for the for loop

with TEXT_IO; use TEXT_IO; procedure LAUNCH is

type COUNTDOWN is ( TEN, NINE, EIGHT, SEVEN, SIX, FIVE, FOUR, THREE, TWO, ONE, BLASTOFF); package COUNTDOWN_IO is new TEXT_IO.ENUMERATION_IO (COUNTDOWN);

begin -- Blastoff for COUNTER in COUNTDOWN loop PUT (COUNTER); NEW_LINE; delay 1.0; end loop; end LAUNCH; -- wait at least 1 second

Alternate ways of expressing range in loop structures : for COUNTER in TEN..BLASTOFF loop for COUNTER in COUNTDOWN range TEN..BLASTOFF loop for COUNTER in COUNTDOWNFIRST..COUNTDOWNLAST loop for COUNTER in COUNTDOWNRANGE loop

ADE

23

While loop used for staying in a loop until some unpredictable condition occurs

General form :

while boolean_expression loop

statements

end loop;

ADE

24

-- Sample program for the while loop with TEXT_IO; package FLOAT_IO is new TEXT_IO.FLOAT_IO (FLOAT); with TEXT_IO, FLOAT_IO; use TEXT_IO, FLOAT_IO; procedure BUDGET is -- A budget program to keep track of the remaining amount in a budget -- and the amount of purchases. AMOUNT_TO_SPEND, AMOUNT_LEFT :FLOAT; TOTAL_SPENT, PURCHASE : FLOAT; begin PUT_LINE ( The budget program has started to execute ); PUT_LINE ( Type the amount to spend in the budget ); GET (AMOUNT_TO_SPEND); NEW_LINE; PUT (AMOUNT_TO_SPEND); NEW_LINE; AMOUNT_LEFT := AMOUNT_TO_SPEND; TOTAL_SPENT := 0.0; while AMOUNT_LEFT > 0.0 loop PUT_LINE ( Type the cost of the next purchase ); GET (PURCHASE); NEW_LINE; PUT (PURCHASE); NEW_LINE; AMOUNT_LEFT := AMOUNT_LEFT PURCHASE; TOTAL_SPENT := TOTAL_SPENT + PURCHASE; NEW_LINE; PUT ( Amount left in the budget is ); PUT (AMOUNT_LEFT); NEW_LINE; PUT ( Amount of purchases is ); PUT (TOTAL_SPENT); NEW_LINE; end loop; end BUDGET;

ADE

25

Unconditional Transfer

- goto statement immediately transfers control to another part of the program, which has been labeled with a name.

Example : <<INFINITE>> PUT_LINE (" I will not use goto statements "); goto INFINITE;

- exit statement allows transfer out of a loop in the middle of the loop instead of at the top of the loop. exit;

ADE

26

User-Defined Types

Enumerated Data Types contains a detailed list of the values or identifiers that make up the data type. They can be Numeric, Character, or Identifier values.

General form of declaration is type data type name is (list of values);

Example :
type WEEK_DAY is (MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY); type ROMAN_NUMERALS is ('I', 'V', 'X', 'L', 'C'); type GRADES is ('A', 'B', 'C', 'D', PASS, FAIL, NONCREDIT);

Data declaration :
DAY : WEEK_DAY; GOLF_DAY : constant WEEK_DAY := SATURDAY; MY_GRADE : GRADES := PASS;

Pre-defined enumeration types


type BOOLEAN is (FALSE, TRUE); type CHARACTER is (NUL, SOH, .. '0', '1', ..'A',..'a', .DEL, '.y');

Operations Relational operators Successor operator Predecessor operator Pos and Val

ADE

27

Attributes of the Enumerated Data Type 'FIRST 'LAST 'RANGE Examples : WEEKDAY'FIRST has a value of MONDAY WEEKDAY'LAST has a value of FRIDAY Usage: for I in MONDAY.. FRIDAY loop -- statements end loop; is better written as for I in WEEKDAY'FIRST.. WEEKDAY'LAST loop -- statements end loop; OR for I in WEEKDAY'RANGE loop -- statements end loop; 'MIN 'MAX 'PRED 'SUCC

ADE

28

-- A sample proram to demonstrate enumerated types with TEXT_IO; use TEXT_IO; procedure FLIGHT_INFORMATION is -- A program to provide flight information on the type of plane, -- the kind of meal, and the time of flight type DAY_TYPE is ( SUN, MON, TUE , WED, THU, FRI, SAT); type PLANE_TYPE is (BOEING_747, DOUGLAS_DC_8, LOCKHEED_1011); type MEAL_TYPE is ( BREAKFAST, LUNCH, SNACKS, DINNER); type TIME_TYPE is (FIVE_PM, THREE_PM); -- Package instantiations are done here... package DAY_IO is new ENUMERATION_IO ( DAY_TYPE); package PLANE_IO is new ENUMERATION_IO ( PLANE_TYPE); package MEAL_IO is new ENUMERATION_IO ( MEAL_TYPE); package TIME_IO is new ENUMERATION_IO ( TIME_TYPE); use DAY_IO, PLANE_IO, MEAL_IO, TIME_IO; DAY : DAY_TYPE; PLANE : PLANE_TYPE; MEAL : MEAL_TYPE; TIME : TIME_TYPE; begin PUT_LINE ( " Flight information program has started .."); PUT_LINE ( " Type the three letter initial for the day"); GET (DAY); NEW_LINE; PUT (" Flight information for "); PUT (DAY); NEW_LINE; case DAY is when MON..FRI => PLANE := BOEING_747; TIME := FIVE_PM; MEAL := DINNER; when others => PLANE := DOUGLAS_DC_8; TIME := THREE_PM; MEAL := SNACKS; end case; PUT (" Today's plane is a "); PUT (PLANE); NEW_LINE; PUT (" It will leave at "); PUT (TIME); NEW_LINE; PUT (" We will serve "); PUT(MEAL); NEW_LINE; end FLIGHT_INFORMATION;

ADE

29

Subtype Consists of a subset of values of a type. A constraint upon an existing type

General form of declaration : subtype data type name is base data type name range first value..last value; Example : subtype CAPITAL_LETTERS is CHARACTER range 'A'..'Z'; subtype NATURAL is INTEGER range 0..INTEGER'LAST; subtype POSITIVE is INTEGER range 1..INTEGER'LAST;

subtype PERSONS_AGE is float range 0.0 .. 120.0; AGE : PERSONS_AGE; DRINKING_AGE: constant PERSONS_AGE := 21.0; AGE := 121.0; -- constraint error

ADE

30

Derived types A derived data type creates a new type from an existing 'parent type'. General form of declaration is : type derived type name is new parent type name [range first_value..last_value]; Example : 1. type COLOR is (WHITE, TAN, BEIGE, GRAY); type STOVE_COLOR is new COLOR range WHITE..BEIGE; type REFRIGERATOR_COLOR is new COLOR;

2.

type MILES_PER_HOUR is new INTEGER range 0..100; type ITEMS_IN_STOCK is new INTEGER range 0..100; SPEED : MILES_PER_HOUR := 65; NUMBER_OF_BOXES : ITEMS_IN_STOCK := 5; NUMBER_OF_BOXES := SPEED; -- illegal; type mismatch

ADE

31

Type Conversion Conversion operator is used to convert between all Numeric data types and related subtypes General form : data type name( data object name) Example : TEMPERATURE : FLOAT := 32.0; BOILING : constant INTEGER := 212; HEIGHT : INTEGER; MT_WHITNEY : constant FLOAT := 14496.1; We can state, TEMPERATURE := FLOAT ( BOILING); HEIGHT := INTEGER (MT_WHITNEY);

ADE

32

Composite Data Structures

Arrays are an ordered collection of data items, each of which has the same data type.

General form of declaration: type array type name is array (index definition) of component type definition;

To refer to an element in an array, the general form of reference is array object name (array index value);

Example : 1. type PRODUCTS_ARRAY is array (INTEGER range 1.. 31) of INTEGER; NUMBER_OF_PRODUCTS_SOLD : PRODUCTS_ARRAY; NUMBER_OF_PRODUCTS_SOLD (1) := 5_000;

2. type PLACES is (INLET, PUMP, RADIATOR, ROOM, OUTLET); type TEMPERATURE_TYPE is array (PLACES range INLET .. OUTLET ) of FLOAT; TEMPERATURES : TEMPERATURE_TYPE; Operations on arrays := for assignment = for test on equality /= for test on inequality

ADE

33

Assigning to the elements of an array

Positional notation : each element is assigned a value from a list of values, with the first value going to the first element etc. Example : TEMPERATURES : TEMPERATURE_TYPE := ( 50.0, 60.0, 70.0, 65.0, 63.0);

Named notation : indices are named in any position or order Example : TEMPERATURES : TEMPERATURE_TYPE := (INLET => 50.0, PUMP => 60.0, RADIATOR => 70.0, ROOM => 65.0, OUTLET => 63.0); To set the elements of an array to the same value : for PLACE in PLACES loop TEMPERATURES( PLACE) := 35.0; end loop; OR TEMPERATURES : TEMPERATURE_TYPE := (INLET..OUTLET => 0.0); OR TEMPERATURES : TEMPERATURE_TYPE := (others => 0.0);

Constant arrays : EXPECTED_TEMPERATURES : constant TEMPERATURE_TYPE := (INLET => 50.0, OUTLET => 60.0, others => 65.0);

ADE

34

-- Sample program for a Single Dimensional Array with TEXT_IO; use TEXT_IO; procedure TEMPERATURE_AVERAGE is
-- A program to calculate the average temperature over a number of different places

type PLACES is ( INLET, PUMP, RADIATOR, ROOM, OUTLET); subtype TEMPERATURE_TYPE is FLOAT range 0.0 ..212.0; type TEMPERATURE_ARRAY is array (PLACES) of TEMPERATURE_TYPE;

package PLACE_IO is new ENUMERATION_IO (PLACES); package TEMPERATURE_IO is new FLOAT_IO ( TEMPERATURE_TYPE); use PLACE_IO; use TEMPERATURE_IO; TEMPERATURES : TEMPERATURE_ARRAY; SUM : FLOAT := 0.0; AVERAGE : TEMPERATURE_TYPE; LENGTH : INTEGER; begin PUT_LINE ( Temperature average program has started to execute ); for I in PLACES loop PUT ( Type temperature for ); PUT (I); NEW_LINE; GET (TEMPERATURES (I)); NEW_LINE; PUT (TEMPERATURES (I)); NEW_LINE; SUM := SUM + TEMPERATURES (I); end loop; LENGTH := PLACES LENGTH; AVERAGE := SUM/ FLOAT (LENGTH); PUT ( Average temperature is ); PUT ( AVERAGE); NEW_LINE; end TEMPERATURE_AVERAGE;

ADE

35

Two-Dimensional Arrays

The 4 consistent combinations for writing the aggregates are : 1. Positional notation for the rows and the columns 2. Named notation for the rows and positional notation for the columns 3. Positional notation for the columns and named notation for the columns 4. Named notation for the rows and columns
Example : A := (( 2,7,5), (6,3,2)); OR A:= (1=> (2,7,5), 2=>(6,3,2)); -- combined named and positional notation OR A:= (1=>(1=>2, 2=>7, 3=>5), 2=> (1=>6, 2=>3, 3=>2)); -- named notation Useful attributes for an n-dimensional array : ARRAY_NAMERANGE(n) ARRAY_NAMELENGTH (n) ARRAY_NAMEFIRST (n) ARRAY_NAMELAST (n) -- range of index values for dimension n -- length of the nth dimension -- first index value of the nth dimension -- last index value of the nth dimension -- positional notation

ADE

36

-- Sample procedure to demonstrate the use of 2 dimensional arrays with TEXT_IO; package INTEGER_IO is new TEXT_IO.INTEGER_IO (INTEGER); with TEXT_IO, INTEGER_IO; use TEXT_IO, INTEGER_IO; procedure ADD_MATRICES is -- procedure to add two matrices
type MAT_TYPE is array (INTEGER range 1..2, INTEGER range 1..3) of INTEGER;

A, B, C : MAT_TYPE; begin PUT(" The ADD_MATRICES program has started to execute .."); NEW_LINE; PUT("Enter 6 values of matrix A in row order "); NEW_LINE; for I in MAT_TYPE'RANGE(1) loop for J in MAT_TYPE'RANGE(2) loop GET(A(I,J)); end loop; end loop; NEW_LINE; PUT("Enter 6 values of matrix B in row order "); NEW_LINE; for I in MAT_TYPE'RANGE(1) loop for J in MAT_TYPE'RANGE(2) loop GET(B(I,J)); end loop; end loop; NEW_LINE; PUT (" The result of adding two matrices is "); NEW_LINE; for I in MAT_TYPE'RANGE(1) loop for J in MAT_TYPE'RANGE(2) loop C(I,J) := A(I,J) + B(I,J); PUT (C(I,J)); end loop; NEW_LINE; end loop; end ADD_MATRICES;

ADE

37

Unconstrained Array Types Unconstrained array types allow Ada programmers to declare arrays that differ in size to be the same type. An unconstrained array type does not include information about the size of the array. Determination of the size of the array is deferred until an array is declared to belong to this unconstrained array type.

Example : type ROW is array (Integer range <>) of Integer; ROW_OF_3 : ROW(1..3); ROW_OF_4 : ROW(1..4); ROW_OF_5 : ROW(0..4); ROW_OF_6 : ROW(-3..2); -- Length is 3 -- Length is 4 -- Length is 5 -- Length is 6

ADE

38

String is a pre-defined data type which is an unconstrained one-dimensional array of characters. -- defined in the package STANDARD subtype POSITIVE is INTEGER range 1.. INTEGER'LAST; type STRING is array (POSITIVE range <>) of CHARACTER;

Example : NAME : STRING (1..10); TOWN : STRING (1..15); -- 10 character string -- 15 character string

ZIP_CODE : STRING (1..6); -- 6 character string HOME : constant STRING := "Santa Barbara"; Operations on strings := = /= & Examples :
TOWN (1..13) := HOME ; TOWN := HOME & " "; NAME := "Judy " & "Smith";

-- for assignment -- test for equality -- test for inequality -- for concatenation

NAME := "Joe"; NAME := "Sammy Davis Junior"; NAME (1..3) := "Joe"; NAME := "Joe ";

-- illegal, too short --illegal too long -- ok, but be careful --ok

ADE

39

Bit Strings

General form : type BIT_STRING is array (POSITIVE range <>) of BOOLEAN;

STATUS_REGISTER : BIT_STRING (1..8) := (1..8 => FALSE); INPUT_REGISTER : BIT_STRING (1..8) := (others => TRUE);

RESULT_REGISTER : BIT_STRING (1..8);

Operations on Bit Strings := = /= & and or not xor and then else or -- for assignment -- for equality -- for inequality -- for concatenation -- for element by element and -- for element by element or -- for element by element not -- for element by element xor -- for element by element and then -- for element by element else or

Example of Logical Operations

RESULT_REGISTER := STATUS_REGISTER and INPUT_REGISTER; RESULT_REGISTER := STATUS_REGISTER or INPUT_REGISTER;

ADE

40

Records

are a collection of data items that may be of different data types.

General form of declaration : type record name type is record record component definitions end record;

Example :
1. type EMPLOYEE_LIST is record FIRST_NAME : STRING (1..25); LAST_NAME : STRING (1..25); SOCIAL_SECURITY_NUMBER : POSITIVE; EMPLOYEE_NUMBER : POSITIVE; end record;

EMPLOYEE: EMPLOYEE_LIST;

Named notation : EMPLOYEE := (LAST_NAME =>('S','m','i','t','h', others=> ' '), EMPLOYEE_NUMBER => 1611; FIRST_NAME => ('M','a','r','y',others=>' '), SOCIAL_SECURITY_NUMBER =>560_54_1650);

ADE

41

2.

type POSITION is record X_COORD : integer; Y_COORD : integer; end record;

POINT : POSITION;

Positional notation : POINT := (1, 2); OR POINT := (others =>2); -- assigns 2 to both components

ADE

42

S-ar putea să vă placă și