CSC 288 · Structured Programming
Our notes
1 min readSelection
if condition then statement else statement
Use begin ... end for more than one statement. No semicolon before else (it would end the if).
if score >= 70 then
grade := 'A'
else if score >= 60 then
grade := 'B'
else if score >= 50 then
grade := 'C'
else if score >= 45 then
grade := 'D'
else if score >= 40 then
grade := 'E'
else
grade := 'F';
This is the usual Nigerian university grading (70 A, 60 B, 50 C, 45 D, 40 E). Order matters: test from the top down.
The case statement
case level of
100: writeln('Fresher');
200, 300: writeln('Stalite');
400, 500: writeln('Final years')
else
writeln('Unknown level')
end;
The selector must be an ordinal type (not real or string in standard Pascal). The else part is a Turbo and Free Pascal extension (otherwise in some compilers).
Repetition
| Loop | Test | Runs at least once? | Use when |
|---|---|---|---|
| while c do S | before | no | number of repeats unknown; may be zero |
| repeat S until c | after | yes | must run once (menus, input checking) |
| for i := a to b do S | counted | no if a > b | number of repeats known |
Examples
Sum of 1 to n with while:
sum := 0; i := 1;
while i <= n do
begin
sum := sum + i;
i := i + 1
end;
For n = 10, sum = 55.
Checking input with repeat:
repeat
write('Score (0-100): ');
readln(score)
until (score >= 0) and (score <= 100);
Counting down with for: for i := 10 downto 1 do write(i, ' ');
Choosing and nesting
Choose the loop that states the intent. Nest loops for tables: a multiplication table uses a for inside a for. Keep each loop's body short; move long bodies into procedures.
Exams usually ask
- Write programs using if, case and the three loops.
- Trace a loop and give its output.
- Compare while and repeat loops.
Common mistake
Changing the control variable inside a for loop, or using its value after the loop. Both are undefined in standard Pascal; use a while loop if the count must change.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.