0% found this document useful (0 votes)
2 views32 pages

Control Structures Reference

The document provides a comprehensive reference on control structures across multiple programming languages, including Visual Basic, Prolog, PL/SQL, Elm, CoffeeScript, and Delphi. Each section covers key concepts such as conditionals, loops, exception handling, and specific syntax examples for each language. The document serves as a guide for understanding and implementing control structures in various programming contexts.

Uploaded by

lizzybenson521
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views32 pages

Control Structures Reference

The document provides a comprehensive reference on control structures across multiple programming languages, including Visual Basic, Prolog, PL/SQL, Elm, CoffeeScript, and Delphi. Each section covers key concepts such as conditionals, loops, exception handling, and specific syntax examples for each language. The document serves as a guide for understanding and implementing control structures in various programming contexts.

Uploaded by

lizzybenson521
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Control Structures

Complete Reference
Visual Basic • Prolog • PL/SQL • Elm • CoffeeScript • Delphi
5 pages per language — syntax, semantics, annotated examples
Table of Contents
1. Visual Basic — Conditionals, Loops, Jump, Exception Handling, With
2. Prolog — Conditionals, Cut, Negation, Loops, Assert/Retract, Meta-Control
3. PL/SQL — Conditionals, Loops, Cursor FOR, CONTINUE/GOTO, Exceptions
4. Elm — Conditionals, Iteration, Recursion, Let/In, Maybe/Result
5. CoffeeScript — Conditionals, Switch, Loops, Comprehensions, Exceptions
6. Delphi — Conditionals, Loops, repeat/until, Break/Continue, Exceptions, With
Visual Basic
Microsoft's event-driven, object-oriented language (.NET)
Control Structures — Complete Reference
1. Conditionals

If / ElseIf / Else / End If


The primary branching construct. All comparisons are short-circuit evaluated.
Dim score As Integer = 85
If score >= 90 Then
[Link]("Grade A")
ElseIf score >= 75 Then
[Link]("Grade B")
ElseIf score >= 60 Then
[Link]("Grade C")
Else
[Link]("Fail")
End If

Select Case
Multi-way branch on a value or expression. Supports ranges and comma-separated values.
Dim day As Integer = 3
Select Case day
Case 1 : [Link]("Monday")
Case 2 : [Link]("Tuesday")
Case 3 : [Link]("Wednesday")
Case 4, 5 : [Link]("Thu or Fri")
Case 6 To 7 : [Link]("Weekend")
Case Else : [Link]("Unknown")
End Select

Select Case also accepts strings, chars, and boolean expressions. Use 'Case Is > value' for relational
matching.
2. Loops

For … Next
Count-controlled loop. The Step keyword controls the increment (default 1).
For i As Integer = 1 To 10 Step 2
[Link](i) ' 1 3 5 7 9
Next

For Each … Next


Iterate every element in a collection or array without an index.
Dim langs() As String = {"VB", "C#", "F#"}
For Each lang As String In langs
[Link](lang)
Next

While … End While (pre-test)


Repeats while the condition is True. Body may never execute if condition starts False.
Dim n As Integer = 1
While n <= 5
[Link](n & " ")
n += 1
End While ' output: 1 2 3 4 5

Do … Loop (Until / While variants)


Post-test loop — body always runs at least once. Use Until or While at the Loop line.
Dim x As Integer = 0
Do
x += 1
[Link](x)
Loop Until x = 3 ' prints 1 2 3

Dim y As Integer = 1
Do While y < 8
y *= 2
Loop ' y = 8
3. Jump & Transfer

Exit For / Exit While / Exit Do


Immediately exits the innermost enclosing loop.
For i As Integer = 1 To 100
If i * i > 50 Then Exit For
[Link](i)
Next

Continue For / Continue While / Continue Do


Skips the rest of the current iteration and moves to the next.
For i As Integer = 1 To 10
If i Mod 3 = 0 Then Continue For ' skip multiples of 3
[Link](i & " ") ' 1 2 4 5 7 8 10
Next

GoTo
Unconditional jump to a labelled line. Use sparingly — structured flow is preferred.
Dim flag As Boolean = True
If flag Then GoTo Handler
[Link]("not reached")
Handler:
[Link]("jumped to handler")

Return
Exits a Sub or Function, optionally returning a value.
Function IsEven(n As Integer) As Boolean
If n Mod 2 = 0 Then Return True
Return False
End Function

[Link](IsEven(4)) ' True


4. Exception Handling

Try / Catch / Finally / End Try


Structured error handling. Multiple Catch blocks handle different exception types.
Try
Dim arr() As Integer = {1, 2, 3}
[Link](arr(10)) ' throws IndexOutOfRangeException
Catch ex As IndexOutOfRangeException
[Link]("Index error: " & [Link])
Catch ex As Exception
[Link]("General error: " & [Link])
Finally
[Link]("Cleanup always runs")
End Try

Throw
Re-raises the current exception or throws a new one.
Sub ValidateAge(age As Integer)
If age < 0 Then
Throw New ArgumentException("Age must be non-negative")
End If
End Sub

5. With Block

With … End With


Removes repetition when accessing multiple members of the same object.
Dim p As New Person()
With p
.FirstName = "Philip"
.LastName = "Daniels"
.Age = 30
.Email = "philip@[Link]"
End With
[Link]([Link] & " " & [Link])

With blocks can be nested. The inner With takes precedence over the outer one.
Prolog
Logic programming — control through unification and backtracking
Control Structures — Complete Reference

PHILIP OKON AKPAN


Matric NO.: 0633
1. Conditionals

If-Then ( -> )
The soft-cut operator. Commits to the then-branch if the condition succeeds.
sign(X, positive) :- X > 0, !.
sign(X, negative) :- X < 0, !.
sign(0, zero).

?- sign(-7, S). % S = negative

If-Then-Else ( -> ; )
Evaluates Else branch when Condition fails. Prevents spurious backtracking into Condition.
classify(X, Result) :-
( X > 0
-> Result = positive
; X < 0
-> Result = negative
; Result = zero
).

?- classify(0, R). % R = zero

Disjunction ( ; )
Either branch may succeed; backtracking explores both alternatives.
vowel(X) :- (X = a ; X = e ; X = i ; X = o ; X = u).

?- vowel(e). % true
?- vowel(b). % false
2. Cut & Negation

! (cut)
Commits to the current clause; prunes all remaining choice points for the predicate.
% Without cut, max/3 would backtrack into the second clause
max(X, Y, X) :- X >= Y, !.
max(_, Y, Y).

?- max(5, 3, M). % M = 5, never tries second clause

fail
Always fails. Combined with side effects it drives iteration over all solutions.
print_all(List) :-
member(X, List),
write(X), nl,
fail.
print_all(_). % base case: succeed after all elements printed

?- print_all([a, b, c]). % prints a b c

\+ (negation as failure)
Succeeds when Goal cannot be proved. Implements closed-world assumption.
likes(mary, food).
likes(mary, wine).

dislikes(P, X) :- \+ likes(P, X).

?- dislikes(mary, beer). % true (unprovable = false under CWA)


?- dislikes(mary, food). % false (provable)
3. Loops via Recursion & Built-ins

Recursive predicate
The idiomatic loop in Prolog. A base case + recursive case replace iteration.
sum_list([], 0).
sum_list([H|T], Sum) :-
sum_list(T, Rest),
Sum is H + Rest.

?- sum_list([1,2,3,4], S). % S = 10

between/3
Generates or tests integers in an inclusive range. Use with fail to iterate.
print_range(Lo, Hi) :-
between(Lo, Hi, X),
write(X), write(' '),
fail.
print_range(_, _).

?- print_range(1, 5). % 1 2 3 4 5

forall/2
Succeeds when Condition holds for every solution of Generator.
?- forall(member(X, [2,4,6,8]), 0 is X mod 2).
% true -- every element is even

?- forall(member(X, [2,3,6]), 0 is X mod 2).


% false -- 3 fails the condition

findall / bagof / setof


Collect all solutions to a goal into a list.
age(alice, 30). age(bob, 25). age(carol, 30).

?- findall(X, age(X,_), L). % L = [alice,bob,carol]


?- setof(X, Y^age(X,Y), L). % L = [alice,bob,carol] (sorted/unique)
?- bagof(X, age(X,30), L). % L = [alice,carol]
4. Dynamic Control

assert / asserta / assertz


Add new facts or rules to the database at runtime.
:- dynamic counter/1.
counter(0).

increment :-
retract(counter(N)),
N1 is N + 1,
assertz(counter(N1)).

?- increment, increment, counter(X). % X = 2

retract / retractall
Remove matching clauses from the dynamic database.
:- dynamic fact/1.
:- assertz(fact(a)).
:- assertz(fact(b)).
:- assertz(fact(c)).

:- retract(fact(b)).
:- retractall(fact(_)). % removes all remaining facts

5. Meta-Control

call/N
Calls a goal dynamically. Essential for higher-order programming.
apply_to_all(_, []).
apply_to_all(Goal, [H|T]) :-
call(Goal, H),
apply_to_all(Goal, T).

?- apply_to_all(write, [1,2,3]). % prints 1 2 3

once/1
Executes goal but commits to the first solution, suppressing backtracking.
?- once(member(X, [a,b,c])). % X = a (only first solution)
PL/SQL
Oracle's procedural extension to SQL for server-side logic
Control Structures — Complete Reference

PAUL IHECHI ALAGBA


1. Conditionals

IF / ELSIF / ELSE / END IF


Standard conditional. NULL-safe: a NULL condition falls through to ELSE.
DECLARE
salary NUMBER := 72000;
band VARCHAR2(20);
BEGIN
IF salary > 120000 THEN band := 'Senior';
ELSIF salary > 80000 THEN band := 'Mid-Senior';
ELSIF salary > 50000 THEN band := 'Mid';
ELSE band := 'Junior';
END IF;
DBMS_OUTPUT.PUT_LINE('Band: ' || band);
END;

CASE (simple form)


Switch on a single selector expression. Cleaner than nested IF for discrete values.
DECLARE grade CHAR(1) := 'B';
BEGIN
CASE grade
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Distinction');
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Merit');
WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Pass');
ELSE DBMS_OUTPUT.PUT_LINE('Fail');
END CASE;
END;

CASE (searched form)


Each WHEN clause contains a full boolean condition — equivalent to IF/ELSIF.
DECLARE score NUMBER := 88;
BEGIN
CASE
WHEN score >= 90 THEN DBMS_OUTPUT.PUT_LINE('A');
WHEN score >= 80 THEN DBMS_OUTPUT.PUT_LINE('B');
WHEN score >= 70 THEN DBMS_OUTPUT.PUT_LINE('C');
ELSE DBMS_OUTPUT.PUT_LINE('D');
END CASE;
END;
2. Loops
Basic LOOP … END LOOP
Infinite loop. Must use EXIT or EXIT WHEN to terminate; suitable for polling patterns.
DECLARE i NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
i := i + 1;
EXIT WHEN i > 5;
END LOOP;
END;

WHILE … LOOP
Pre-test loop — condition checked before each iteration. Body may not execute.
DECLARE
total NUMBER := 0;
n NUMBER := 1;
BEGIN
WHILE n <= 100 LOOP
total := total + n;
n := n + 1;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Sum 1-100: ' || total); -- 5050
END;

Numeric FOR … LOOP


Counter declared implicitly; cannot be modified inside the loop body.
BEGIN
FOR i IN REVERSE 1..5 LOOP -- counts down: 5 4 3 2 1
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
3. Cursor FOR Loops
Implicit cursor FOR loop
The preferred way to process query results. Open, fetch, and close are automatic.
BEGIN
FOR emp IN (SELECT employee_id, first_name, salary
FROM employees
WHERE department_id = 10
ORDER BY salary DESC)
LOOP
DBMS_OUTPUT.PUT_LINE(emp.first_name || ': $' || [Link]);
END LOOP;
END;

Explicit cursor FOR loop


Name the cursor for reuse or parameterisation.
DECLARE
CURSOR high_earners IS
SELECT first_name, salary FROM employees WHERE salary > 80000;
BEGIN
FOR rec IN high_earners LOOP
DBMS_OUTPUT.PUT_LINE(rec.first_name || ' earns ' || [Link]);
END LOOP;
END;

4. CONTINUE & GOTO


CONTINUE / CONTINUE WHEN
Skip the rest of the current loop iteration (Oracle 11g+).
BEGIN
FOR i IN 1..10 LOOP
CONTINUE WHEN MOD(i, 2) = 0; -- skip even numbers
EXIT WHEN i = 9; -- stop before 9
DBMS_OUTPUT.PUT_LINE(i); -- prints 1 3 5 7
END LOOP;
END;

GOTO
Unconditional branch to a label within the same block (use sparingly).
BEGIN
GOTO log_and_exit;
DBMS_OUTPUT.PUT_LINE('unreachable');
<<log_and_exit>>
DBMS_OUTPUT.PUT_LINE('Reached label');
END;
5. Exception Handling
EXCEPTION … WHEN
Catches predefined Oracle exceptions by name.
DECLARE
v_result NUMBER;
BEGIN
v_result := 100 / 0;
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Cannot divide by zero');
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Value error occurred');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected: ' || SQLERRM);
RAISE; -- re-raise to caller
END;

User-defined exceptions
Declare, raise, and catch your own named exceptions.
DECLARE
salary_too_low EXCEPTION;
v_sal NUMBER := 800;
BEGIN
IF v_sal < 1000 THEN
RAISE salary_too_low;
END IF;
DBMS_OUTPUT.PUT_LINE('OK');
EXCEPTION
WHEN salary_too_low THEN
DBMS_OUTPUT.PUT_LINE('Salary below minimum threshold');
END;

RAISE_APPLICATION_ERROR
Return a custom ORA- error number and message to the caller.
IF v_age < 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Age cannot be negative');
END IF;
Elm
Purely functional language for reliable front-end web
applications
Control Structures — Complete Reference

FRANCIS ALOYSIUS
DE-2022/PT/0606
1. Conditionals

if / then / else
An expression, not a statement. Both branches must exist and return the same type.
classify : Int -> String
classify n =
if n > 0 then
"positive"
else if n < 0 then
"negative"
else
"zero"

-- classify -3 => "negative"

case … of (pattern matching)


Exhaustively matches on any type — the primary branching tool in Elm.
type Shape
= Circle Float
| Rectangle Float Float
| Triangle Float Float Float

area : Shape -> Float


area shape =
case shape of
Circle r -> pi * r ^ 2
Rectangle w h -> w * h
Triangle a b c ->
let s = (a + b + c) / 2
in sqrt (s * (s-a) * (s-b) * (s-c))

The Elm compiler enforces exhaustive case branches — every possible value must be handled,
preventing runtime errors.
2. Iteration (no loops — functional style)

Elm has no for/while loops. Repetition is expressed through higher-order functions and recursion.

[Link] — transform
Apply a function to every element, returning a new list.
double : Int -> Int
double x = x * 2

[Link] double [1, 2, 3, 4, 5]


-- [2, 4, 6, 8, 10]

-- With anonymous function:


[Link] (\x -> x ^ 2) [1, 2, 3]
-- [1, 4, 9]

[Link] — select
Keep only elements where the predicate returns True.
isEven : Int -> Bool
isEven n = modBy 2 n == 0

[Link] isEven [1, 2, 3, 4, 5, 6]


-- [2, 4, 6]

[Link] / [Link] — reduce


Accumulate a list into a single value from the left or right.
-- Sum a list
[Link] (+) 0 [1, 2, 3, 4, 5] -- 15

-- Build a reversed list


[Link] (::) [] [1, 2, 3] -- [3, 2, 1]

-- Product
[Link] (*) 1 [1, 2, 3, 4] -- 24
3. Recursion

Simple recursion
The Elm equivalent of a loop. Define a base case and a recursive case.
factorial : Int -> Int
factorial n =
if n <= 1 then 1
else n * factorial (n - 1)

-- factorial 6 => 720

Tail-recursive accumulator pattern


Pass an accumulator to avoid stack overflow on large inputs.
sumList : List Int -> Int
sumList xs = sumHelper xs 0

sumHelper : List Int -> Int -> Int


sumHelper xs acc =
case xs of
[] -> acc
x :: rest -> sumHelper rest (acc + x)

-- sumList [1,2,3,4,5] => 15

4. Local Bindings

let … in
Introduce named sub-expressions scoped to the body. Essential for readable functions.
distanceBetween : (Float,Float) -> (Float,Float) -> Float
distanceBetween (x1,y1) (x2,y2) =
let
dx = x2 - x1
dy = y2 - y1
sumSquares = dx^2 + dy^2
in
sqrt sumSquares
5. Controlled Flow (Maybe & Result)

Maybe — optional values


Replaces null checks. Nothing signals absence; Just wraps a value.
safeHead : List a -> Maybe a
safeHead list =
case list of
[] -> Nothing
x :: _ -> Just x

-- safeHead [] => Nothing


-- safeHead [1,2,3] => Just 1

[Link] — chained optionals


Chain operations that may fail without nested case expressions.
safeDiv : Int -> Int -> Maybe Int
safeDiv _ 0 = Nothing
safeDiv x y = Just (x // y)

compute : Int -> Int -> Maybe Int


compute a b =
safeDiv a b
|> [Link] (\r -> Just (r + 10))
|> [Link] (\r -> safeDiv r 2)

-- compute 20 4 => Just 7


-- compute 20 0 => Nothing

Result — success or error


Like Maybe but the Err branch carries an error description.
parseAge : String -> Result String Int
parseAge str =
case [Link] str of
Nothing -> Err ("Not a number: " ++ str)
Just n ->
if n < 0 then Err "Age must be positive"
else Ok n

-- parseAge "25" => Ok 25


-- parseAge "abc" => Err "Not a number: abc"
CoffeeScript
A concise language that compiles to clean JavaScript
Control Structures —

ECHEBE EMMANUEL
DE:2022/PT/0621
1. Conditionals

if / else if / else
No parentheses or braces needed. Indentation defines blocks.
temperature = 28

if temperature > 35
[Link] "Very hot"
else if temperature > 25
[Link] "Warm"
else if temperature > 15
[Link] "Mild"
else
[Link] "Cold"

unless
Syntactic sugar for 'if not'. Improves readability for negative conditions.
isAuthenticated = false

unless isAuthenticated
[Link] "Access denied — please log in"

# equivalent to:
if not isAuthenticated
[Link] "Access denied — please log in"

Postfix if / unless
One-liner guards placed after the action for compact inline conditions.
[Link] "adult" if age >= 18
[Link] "minor" unless age >= 18

sendAlert() if criticalError
skipStep() unless stepRequired

Ternary expression
if/then/else on a single line returning a value.
status = if connected then "online" else "offline"
discount = if vip then 0.20 else 0.05
label = if score > 50 then "pass" else "fail"
2. switch / when

switch / when / else


No fall-through by default. when accepts comma-separated values.
role = "admin"

switch role
when "admin"
[Link] "Full access"
when "editor", "author"
[Link] "Write access"
when "viewer"
[Link] "Read only"
else
[Link] "Unknown role"

3. Loops

for … in (arrays)
Iterate over array elements. Optional when clause filters items inline.
scores = [45, 72, 90, 33, 88]

for score in scores when score >= 70


[Link] "Pass: #{score}"

# Shorthand with index:


for score, i in scores
[Link] "#{i}: #{score}"

for … of (objects)
Iterate key-value pairs of a plain object.
person = { name: "Philip", city: "Port Harcourt", role: "dev" }

for key, value of person


[Link] "#{key} = #{value}"
4. while, until, loop

while
Repeats while the condition is true. Standard pre-test behaviour.
queue = ['task1', 'task2', 'task3']

while [Link] > 0


current = [Link]()
[Link] "Processing: #{current}"

until
Repeats UNTIL the condition becomes true (loop while NOT condition).
retries = 0

until retries >= 5 or connected


connect()
retries++

[Link] "Connected after #{retries} attempt(s)"

loop (infinite loop)


No condition — runs forever. Use break or break if to exit.
attempts = 0

loop
attempts++
result = tryConnect()
break if [Link] or attempts >= 10

[Link] "Done after #{attempts} attempts"

List comprehensions (postfix for)


One-liner that produces a new array — the CoffeeScript version of map/filter.
numbers = [1..10]
squares = (n * n for n in numbers)
evens = (n for n in numbers when n % 2 is 0)
labels = ("item-#{n}" for n in [1..5])

# squares => [1,4,9,16,25,36,49,64,81,100]


# evens => [2,4,6,8,10]
# labels => ['item-1','item-2','item-3','item-4','item-5']
5. Exception Handling & Loop Control

try / catch / finally


Maps directly to JavaScript try/catch/finally. No type annotations on catch.
readConfig = (path) ->
try
data = [Link] path, 'utf8'
[Link] data
catch err
if [Link] is 'ENOENT'
[Link] "File not found: #{path}"
else
[Link] "Parse error: #{[Link]}"
null
finally
[Link] "readConfig finished"

throw
Raises an exception. Works identically to JavaScript throw.
validateUser = (user) ->
throw new Error('Name required') unless [Link]
throw new Error('Age must be > 0') unless [Link] > 0
user

break / continue
break exits the loop; continue skips to the next iteration.
for n in [1..20]
continue if n % 2 is 0 # skip even numbers
break if n > 11 # stop after 11
[Link] n # prints 1 3 5 7 9 11

CoffeeScript's 'do' keyword creates an immediately-invoked function scope, useful for closing over loop
variables.
Delphi
Object Pascal compiler — Windows, macOS, iOS,
Android & Linux
Control Structures — Complete Reference

FAVOUR NJOKU
1. Conditionals

if … then … else
Single-statement branches need no begin/end; multi-statement blocks require them.
var score: Integer := 78;
begin
if score >= 90 then
WriteLn('A')
else if score >= 75 then
WriteLn('B')
else if score >= 60 then
WriteLn('C')
else
begin
WriteLn('F');
WriteLn('Consider re-sitting');
end;
end;

case … of
Branch on any ordinal type (integer, char, enum, boolean). Supports value ranges.
var dayNum: Integer := 4;
begin
case dayNum of
1 : WriteLn('Monday');
2 : WriteLn('Tuesday');
3 : WriteLn('Wednesday');
4, 5 : WriteLn('Thursday or Friday');
6..7 : WriteLn('Weekend');
else
WriteLn('Invalid day');
end;
end;
2. Loops

for … to / downto … do
Counter is implicit (integer only). Step is always 1 or -1.
var i: Integer;
begin
// Count up
for i := 1 to 5 do
Write(i, ' '); // 1 2 3 4 5
WriteLn;

// Count down
for i := 5 downto 1 do
Write(i, ' '); // 5 4 3 2 1
WriteLn;
end;

for … in … do (enumerator)
Iterate over arrays, sets, strings, or any IEnumerable (Delphi 2005+).
var
langs : TArray<string> := ['Delphi', 'C#', 'Python'];
ch : Char;
begin
for var lang in langs do
WriteLn(lang);

for ch in 'Hello' do // iterate characters of a string


Write(ch, '-'); // H-e-l-l-o-
end;

while … do
Pre-test loop. Body never executes if condition is False on first check.
var n, total: Integer;
begin
n := 1; total := 0;
while n <= 100 do
begin
total := total + n;
Inc(n);
end;
WriteLn('Sum 1..100 = ', total); // 5050
end;
3. repeat … until & Loop Control

repeat … until
Post-test loop — body always runs at least once. Exits when condition becomes True.
var input: string;
begin
repeat
Write('Enter "yes" to continue: ');
ReadLn(input);
until LowerCase(input) = 'yes';
WriteLn('Confirmed!');
end;

Break
Immediately exits the innermost loop.
var i: Integer;
begin
for i := 1 to 1000 do
begin
if i * i > 200 then Break;
WriteLn(i); // prints 1..14
end;
end;

Continue
Skips the rest of the current iteration and jumps to the next.
var i: Integer;
begin
for i := 1 to 15 do
begin
if i mod 3 = 0 then Continue; // skip multiples of 3
Write(i, ' '); // 1 2 4 5 7 8 10 11 13 14
end;
end;

Break and Continue work inside for, while, and repeat loops. They always affect the innermost
enclosing loop.
4. Exception Handling

try … except … end


Catch specific exception classes. Use 'on E: EClass do' for typed handling.
var x, y: Integer;
begin
x := 10; y := 0;
try
WriteLn(x div y);
except
on E: EDivByZero do
WriteLn('Division by zero: ', [Link]);
on E: EInvalidOp do
WriteLn('Invalid operation: ', [Link]);
on E: Exception do
WriteLn('Unknown error: ', [Link]);
end;
end;

try … finally … end


Guarantees cleanup code runs whether an exception occurred or not.
var F: TFileStream;
begin
F := [Link]('[Link]', fmOpenRead);
try
// process file...
ProcessStream(F);
finally
[Link]; // always executed
end;
end;

5. With Block

with … do
Access record fields or object properties without repeating the qualifier.
with MainForm do
begin
Caption := 'Control Structures Demo';
Width := 800;
Height := 600;
Position := poScreenCenter;
Visible := True;
end;

Avoid nested 'with' blocks — they create ambiguity when both objects share a member name. Use
explicit variable references instead.

You might also like