Published by Patrick Mutisya · 14 days ago
Define and use non‑composite user‑defined types in a program.
Non‑composite types are data types that are not built from other types. In the Cambridge A‑Level syllabus they include:
An enumerated type is a set of named values. Each value is called an enumeration constant. The underlying representation is usually an integer, but the programmer works with the symbolic names.
Syntax (Pascal‑like)
type
Colour = (Red, Green, Blue);
In this example Colour can only take one of the three values Red, Green or Blue.
Common operations:
c := Red;if c = Blue then …succ / pred in Pascal): \$\text{next} = \text{succ}(\text{current})\$A subrange type restricts the values of an existing ordinal type (e.g., integer or char) to a contiguous subset.
Syntax
type
Score = 0..100; { integer subrange }
Grade = 'A'..'F'; { character subrange }
Variables of type Score can only hold values between 0 and 100 inclusive. Attempting to assign a value outside the range causes a run‑time error.
A type synonym creates a new name for an existing type. It does not create a new representation, but it improves code readability and can be used to enforce abstraction.
Syntax
type
StudentID = integer;
Temperature = real;
After the definition, StudentID and integer are interchangeable, but the name conveys intent.
if status = Open then …).The following Pascal‑style program demonstrates all three non‑composite types.
program ExamResult;
type
Grade = (A, B, C, D, F); { enumerated }
Mark = 0..100; { subrange }
StudentID = integer; { synonym }
var
id : StudentID;
m : Mark;
g : Grade;
function CalculateGrade(m : Mark) : Grade;
begin
case m of
90..100: CalculateGrade := A;
80..89 : CalculateGrade := B;
70..79 : CalculateGrade := C;
60..69 : CalculateGrade := D;
else CalculateGrade := F;
end;
end;
begin
id := 12345;
m := 78;
g := CalculateGrade(m);
writeln('Student ', id, ' scored ', m, ' and received grade ', g);
end.
| Type | Purpose | Typical Syntax | Example \cdot alues |
|---|---|---|---|
| Enumerated | Define a fixed set of named constants | type Name = (Const1, Const2, …); | Colour = (Red, Green, Blue) |
| Subrange | Restrict an ordinal type to a contiguous interval | type Name = low..high; | Score = 0..100 |
| Type synonym | Give a meaningful name to an existing type | type NewName = ExistingType; | StudentID = integer |
Day for the seven days of the week. Write a procedure that prints “Weekend” if the day is Saturday or Sunday, otherwise prints “Weekday”.Age that allows values from 0 to 120. Write a function that returns true if a given Age is a legal voting age (≥18).type Money = real; and type Money = 0..1000; in terms of allowed values and program safety.