0% found this document useful (0 votes)
4 views36 pages

CSC301 UNIT 6a Conditional Statements and Loops

Uploaded by

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

CSC301 UNIT 6a Conditional Statements and Loops

Uploaded by

Ifeoseme Joel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

UNIT 6

Operators
An operator is a symbol that tells the compiler to perform specific mathematical or
logical manipulations. Pascal allows the following types of operators:
· Arithmetic operators
· Relational operators
· Boolean operators
· Bit operators
· Set operators
· String operators

Let us discuss the arithmetic, relational, Boolean and bit operators one by one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by Pascal. Assume
variable A holds 10 and variable B holds 20, then:

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the A - B will give -10


first
* Multiplies both operands A * B will give 200

div Divides numerator by denominator B div A will give 2

mod Modulus Operator AND remainder B mod A will give 0


after an integer division
The following example illustrates the arithmetic operators:

program calculator;
var
a,b,c : integer;
d: real;
begin
a:=21;
b:=10;
c := a + b;
writeln(' Line 1 - Value of c is ', c );
c := a - b;
writeln('Line 2 - Value of c is ', c );
c := a * b;
writeln('Line 3 - Value of c is ', c );
d := a / b;
writeln('Line 4 - Value of d is ', d:3:2 );
c := a mod b;
writeln('Line 5 - Value of c is ' , c );
c := a div b;
writeln('Line 6 - Value of c is ', c );
end.

Please note that Pascal is very strongly typed programming language, so it would
give an error if you try to store the results of a division in an integer type variable.
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of d is 2.10
Line 5 - Value of c is 1
Line 6 - Value of c is 2

When the above code is compiled and executed, it produces the following result:
Relational Operators

Following table shows all the relational operators supported by Pascal. Assume variable
A holds 10 and variable B holds 20, then:

Operator Description Example

= Checks if the values of two operands are (A = B) is not true.


equal or not, if yes, then condition
becomes true.

<> Checks if the values of two operands are (A <> B) is true.


equal or not, if values are not equal, then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand, if
yes, then condition becomes true.

< Checks if the value of left operand is (A < B) is true.


less than the value of right operand, if
yes, then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of right
operand, if yes, then condition becomes
true.

<= Checks if the value of left operand is less (A <= B) is true.


than or equal to the value of right
operand, if yes, then condition becomes
true.
Try the following example to understand all the relational operators available in
Pascal programming language:
program showRelations;
var
a, b: integer;
begin
a := 21;
b := 10;
if a = b then
writeln('Line 1 - a is equal to b' )
else
writeln('Line 1 - a is not equal to b' );
if a < b then
writeln('Line 2 - a is less than b' )
else
writeln('Line 2 - a is not less than b' );
if a > b then
writeln('Line 3 - a is greater than b' )
else
writeln('Line 3 - a is greater than b' );

(* Lets change value of a and b *)


a := 5;
b := 20;

if a <= b then
writeln('Line 4 - a is either less than or equal to b' );
if ( b >= a ) then
writeln('Line 5 - b is either greater than or equal to ' );
end.

When the above code is compiled and executed, it produces the following result:
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
Boolean Operators

Following table shows all the Boolean operators supported by Pascal language. All
these operators work on Boolean operands and produce Boolean results. Assume
variable A holds true and variable B holds false, then:

Operator Description Example

and Called Boolean AND operator. If both the A and B) is false.


operands are true, then condition becomes true.

and then It is similar to the AND operator, however, it (A and then B) is


guarantees the order in which the compiler false.
evaluates the logical expression. Left to right
and the right operands are evaluated only when
necessary.
or Called Boolean OR Operator. If any of the two (A or B) is true.
operands is true, then condition becomes true.

or else It is similar to Boolean OR, however, it (A or else B) is true.


guarantees the order in which the compiler
evaluates the logical expression. Left to right
and the right operands are evaluated only when
necessary.
<= Called Boolean NOT Operator. Used to reverse not (A and B) is
the logical state of its operand. If a condition is true.
true, then Logical NOT operator will make it
false.
The following example illustrates the concept:
program beLogical;
var
a, b: boolean;

begin
a := true; b := false;

if (a and b) then
writeln('Line 1 - Condition is true' ) else
writeln('Line 1 - Condition is not true');
if (a or b) then
writeln('Line 2 - Condition is true' );

(* lets change the value of a and b *)


a := false;
b := true;
if (a and b) then
writeln('Line 3 - Condition is true' ) else
writeln('Line 3 - Condition is not true' );
if not (a and b) then
writeln('Line 4 - Condition is true' );
end.

When the above code is compiled and executed, it produces the following result:

Line 1 - Condition is not true


Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true
Bit Operators

Bitwise operators work on bits and perform bit-by-bit operation. All these operators
work on integer operands and produce integer results. The truth table for bitwise and
(&), bitwise or (|), and bitwise not (~) are as follows:
p q p&q p!q ~p ~q
0 0 0 0 1 1
0 1 0 1 1 0
1 0 1 1 0 0
1 1 0 1 0 1
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by Pascal are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:

Operator Description Example


& Binary AND Operator copies a bit to the result (A & B) will give 12, which is
if it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in (A | B) will give 61, which is
either operand. 0011 1101
! Binary OR Operator copies a bit if it exists in (A ! B) will give 61, which is
either operand. 0011 1101
~ Binary Ones Complement Operator is unary (~A ) will give -60, which is
and has the effect of 'flipping' bits. 1100 0011
<< Binary Left Shift Operator. The left operands A << 2 will give 240, which is
value is moved left by the number of bits 1111 0000
specified by the right operand.

>> Binary Right Shift Operator. The left A >> 2 will give 15, which is
operands value is moved right by the number 0000 1111
of bits specified by the right operand.
Please note that different implementations of Pascal differ in bitwise operators. Free
Pascal, the compiler we used here, however, supports the following bitwise operators:

Operator Operations
s
not Bitwise NOT
and Bitwise AND
or Bitwise OR
xor Bitwise exclusive OR
shl Bitwise shift left
shr Bitwise shift right
<< Bitwise shift left
>> Bitwise shift right

The following example illustrates the concept:

program beBitwise;
var
a, b, c: integer;
begin
a := 60; (* 60 = 0011 1100 *)
b := 13; (* 13 = 0000 1101 *)
c := 0;

c := a and b; (* 12 = 0000 1100 *)


writeln('Line 1 - Value of c is ', c );

c := a or b; (* 61 = 0011 1101 *)
writeln('Line 2 - Value of c is ', c );

c := not a; (* -61 = 1100 0011 *)


writeln('Line 3 - Value of c is ', c );

c := a << 2; (* 240 = 1111 0000 *)


writeln('Line 4 - Value of c is ', c );

c := a >> 2; (* 15 = 0000 1111 *)


writeln('Line 5 - Value of c is ', c );
end.

When the above code is compiled and executed, it produces the following result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is -61
Line 4 - Value of c is 240
Line 5 - Value of c is 15
Operators Precedence in Pascal
Operator precedence determines the grouping of terms in an expression. This affects how
an expression is evaluated. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7. Here,
operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will
be evaluated first.
Operators Precedence
~, not, Highest
*, /, div, mod, and, &
|, !, +, -, or,
=, <>, <, <=, >, >=, in
or else, and then Lowest

Try the following example to understand the operator precedence available in Pascal:
program opPrecedence;
var
a, b, c, d : integer;
e: real;
begin
a := 20;
b := 10;
c := 15;
d := 5;
e := (a + b) * c / d; (* ( 30 * 15 ) / 5 *)
writeln('Value of (a + b) * c / d is : ', e:3:1 );

e := ((a + b) * c) / d; (* (30 * 15 ) / 5 *)
writeln('Value of ((a + b) * c) / d is : ' , e:3:1 );

e := (a + b) * (c / d); (* (30) * (15/5) *)


writeln('Value of (a + b) * (c / d) is : ', e:3:1);

e := a + (b * c) / d; (* 20 + (150/5) *)
writeln('Value of a + (b * c) / d is : ' , e:3:1 );
end.

When the above code is compiled and executed, it produces the following result:
Value of (a + b) * c / d is : 90.0
Value of ((a + b) * c) / d is : 90.0
Value of (a + b) * (c / d) is : 90.0
Value of a + (b * c) / d is : 50.0
Decision Making
This section shows the decision making structure found in Pascal:
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.

Following is the general form of a typical decision making structure found in most
of the programming languages:

Pascal programming language provides the following types of decision making


statements. Click the following links to check their details.
Statement Description

if - then statement An if - then statement consists of a boolean expression


followed by one or more statements.
If-then-else statement An if - then statement can be followed by an optional
else statement, which executes when the boolean
expression is false.
nested if statements You can use one if or else if statement inside another if or
else if statement(s).
case statement A case statement allows a variable to be tested for equality
against a list of values.
case - else statement It is similar to the if-then-else statement. Here, an else
term follows the case statement.
nested case statements You can use one case statement inside another case
statement(s).

if-then Statement

The if-then statement is the simplest form of control statement, frequently used in
decision making and changing the control flow of the program execution.

Syntax

Syntax for if-then statement is:


if condition then S

Where condition is a Boolean or relational condition and S is a simple or compound


statement. Example of an if-then statement is:
if (a <= 20) then
c:= c+1;

If the boolean expression condition evaluates to true, then the block of code inside
the if statement will be executed. If boolean expression evaluates to false, then the
first set of code after the end of the if statement (after the closing end;) will be
executed.

Pascal assumes any non-zero and non-nil values as true, and if it is either zero or nil,
then it is assumed as false value.

Flow Diagram:

Example:
Let us try a complete example that would illustrate the concept:
program ifChecking;
var
{ local variable declaration }
a:integer;
begin
a:= 10;
(* check the boolean condition using if statement *)
if( a < 20 ) then
(* if condition is true then print the following *)
writeln('a is less than 20 ' );
writeln('value of a is : ', a);
end.

When the above code is compiled and executed, it produces the following result:
a is less than 20
value of a is : 10
if-then-else Statement

An if-then statement can be followed by an optional else statement, which executes


when the Boolean expression is false.

Syntax: Syntax for the if-then-else statement is:


if condition then S1 else S2;

Where, S1 and S2 are different statements. Please note that the statement S1 is not
followed by a semicolon. In the if-then-else statements, when the test condition is
true, the statement S1 is executed and S2 is skipped; when the test condition is false,
then S1 is bypassed and statement S2 is executed.

For example,
if color = red then
writeln('You have chosen a red car')
else
writeln('Please choose a color for your car');

If the boolean expression condition evaluates to true, then the if-then block of code
will be executed, otherwise the else block of code will be executed. Pascal assumes
any non-zero and non-nil values as true, and if it is either zero or nil, then it is assumed
as false value.

Flow Diagram:
Example:

Let us try a complete example that would illustrate the concept:

program ifelseChecking;
var
{ local variable definition }
a : integer;
begin
a := 100;
(* check the boolean condition *)
if( a < 20 ) then
(* if condition is true then print the following *)
writeln('a is less than 20' )
else
(* if condition is false then print the following *)
writeln('a is not less than 20' );
writeln('value of a is : ', a);
end.

When the above code is compiled and executed, it produces the following result:
a is not less than 20
value of a is : 100
The if-then-else if-then-else Statement

An if-then statement can be followed by an optional else if-then-else statement, which is


very useful to test various conditions using single if-then-else if statement.
When using if-then, else if-then, else statements there are few points to keep in mind.
· An if-then statement can have zero or one else's and it must come after any else if's.
· An if-then statement can have zero to many else if's and they must come before the else.
· Once an else if succeeds, none of the remaining else if's or else's will be tested.
· No semicolon (;) is given before the last else keyword, but all statements can be
compound statements.

Syntax: of an if-then-else if-then-else statement in Pascal programming language is:


if(boolean_expression 1)then
S1 (* Executes when the boolean expression 1 is true *)
else if( boolean_expression 2) then
S2 (* Executes when the boolean expression 2 is true *)
else if( boolean_expression 3) then
S3 (* Executes when the boolean expression 3 is true *)
else
S4; ( * executes when the none of the above condition is true *)

Example: The following example illustrates the concept:


program ifelse_ifelseChecking;
var
{ local variable definition }
a : integer;
begin
a := 100;
(* check the boolean condition *)
if (a = 10) then
(* if condition is true then print the following *)
writeln('Value of a is 10' )
else if ( a = 20 ) then
(* if else if condition is true *)
writeln('Value of a is 20' )
else if( a = 30 ) then
(* if else if condition is true *)
writeln('Value of a is 30' )
else
(* if none of the conditions is true *)
writeln('None of the values is matching' );
writeln('Exact value of a is: ', a );
end.

None of the values is matching


Exact value of a is: 100
Nested if-then Statements

It is always legal in Pascal programming to nest if-else statements, which means you
can use one if or else if statement inside another if or else if statement(s). Pascal
allows nesting to any level, however, if depends on Pascal implementation on a
particular system.

Syntax:

The syntax for a nested if statement is as follows:


if( boolean_expression 1) then
if(boolean_expression 2)then S1
else
S2;

You can nest else if-then-else in the similar way as you have nested if-then statement.
Please note that, the nested if-then-else constructs gives rise to some ambiguity as to
which else statement pairs with which if statement. The rule is that the else keyword
matches the first if keyword (searching backwards) not already matched by an else
keyword.

The above syntax is equivalent to:


if( boolean_expression 1) then
begin
if(boolean_expression 2)then
S1
else
S2;
end;

It is not equivalent to
if ( boolean_expression 1) then
begin
if exp2 then
S1
end;
else
S2;
Therefore, if the situation demands the later construct, then you must put begin and
end keywords at the right place.

Example:

program nested_ifelseChecking;
var
{ local variable definition }
a, b : integer;
begin
a := 100;
b:= 200;
(* check the boolean condition *)
if (a = 100) then
(* if condition is true then check the following *)
if ( b = 200 ) then
(* if nested if condition is true then print the following *)
writeln('Value of a is 100 and value of b is 200' );

writeln('Exact value of a is: ', a );


writeln('Exact value of b is: ', b );
end.

When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
Case Statement

You have observed that if-then-else statements enable us to implement multiple


decisions in a program. This can also be achieved using the case statement in simpler
way.

Syntax:

case (expression) of
L1 : S1;
L2: S2;
...
...
Ln: Sn;
end;

The syntax of the case statement is:

Where, L1, L2... are case labels or input values, which could be integers, characters,
boolean or enumerated data items. S1, S2, ... are Pascal statements, each of these
statements may have one or more than one case label associated with it. The
expression is called the case selector or the case index. The case index may assume
values that correspond to the case labels.

The case statement must always have an end statement associated with it.

The following rules apply to a case statement:


· The expression used in a case statement must have an integral or enumerated type
or be of a class type in which the class has a single conversion function to an
integral or enumerated type.
· You can have any number of case statements within a case. Each case is followed
by the value to be compared to and a colon.
· The case label for a case must be the same data type as the expression in the case
statement, and it must be a constant or a literal.
· The compiler will evaluate the case expression. If one of the case label's value
matches the value of the expression, the statement that follows this label is
executed. After that, the program continues after the final end.
· If none of the case label matches the expression value, the statement list after the
else or otherwise keyword is executed. This can be an empty statement list. If no
else part is present and no case constant matches the expression value, program
flow continues after the final end.
· The case statements can be compound statements (i.e., a Begin ... End block).

Flow Diagram:
Example:

The following example illustrates the concept:

program checkCase;
var
grade: char;
begin
grade := 'A';

case (grade) of
'A' : writeln('Excellent!' );
'B', 'C': writeln('Well done' );
'D' : writeln('You passed' );
'F' : writeln('Better try again' );
end;
writeln('Your grade is ', grade );
end.

When the above code is compiled and executed, it produces the following result:
Excellent!
Your grade is A

Case Else Statement

The case-else statement uses an else term after the case labels, just like an if-then-else
construct.

Syntax:

The syntax for the case-else statement is:

case (expression) of
L1 : S1;
L2 : S2;
...
...
Ln: Sn;
else
Sm;
end;
Flow Diagram:

Example:

The following example illustrates the concept:

program checkCase;
var
grade: char;
begin
grade := 'F';
case (grade) of
'A' : writeln('Excellent!' );
'B', 'C': writeln('Well done' );
'D' : writeln('You passed' );
else
writeln('You really did not study right!' );
end;
writeln('Your grade is ', grade );
end.

When the above code is compiled and executed, it produces the following result:

You really did not study right!


Your grade is F
Nested Case Statements

It is possible to have a case statement as part of the statement sequence of an outer


case statement. Even if the case constants of the inner and outer case contain
common values, no conflicts will arise.

Syntax:

The syntax for a nested case statement is as follows:

case (ch1) of
'A': begin
writeln('This A is part of outer case' );
case(ch2) of
'A': writeln('This A is part of inner case' );
'B': (* case code *)
...
end; {end of inner case}
end; (* end of case 'A' of outer statement *)
'B': (* case code *)
'C': (* case code *)
...
end; {end of outer case}

Example:

The following program illustrates the concept.


program checknestedCase;
var
a, b: integer;
begin
a := 100;
b := 200;
case (a) of
100: begin
writeln('This is part of outer statement' );
case (b) of
200: writeln('This is part of inner statement' );
end;
end;
end;
writeln('Exact value of a is : ', a );
writeln('Exact value of b is : ', b );
end.

When the above code is compiled and executed, it produces the following result:
This is part of outer switch
This is part of inner switch
Exact value of a is: 100
Exact value of b is: 200
Iteration (Loops)
There may be a situation, when you need to execute a block of code several number
of times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more
complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple


times and following is the general form of a loop statement in most of the
programming languages:

Pascal programming language provides the following types of loop constructs to


handle looping requirements. Click the following links to check their details.
Loop Type Description

while-do loop Repeats a statement or group of statements until a given condition is


true. It tests the condition before executing the loop body.
for-do loop Executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable.
repeat-until loop Like a while statement, except that it tests the condition at the end of
the loop body.
nested loops You can use one or more loop inside any another while, for or repeat
until loop.
while-do loop

A while-do loop statement in Pascal allows repetitive computations till some test
condition is satisfied. In other words, it repeatedly executes a target statement as long
as a given condition is true.

Syntax:

The syntax of a while-do loop is:

while (condition) do S;

Where condition is a Boolean or relational expression, whose value would be true or


false and S is a simple statement or group of statements within BEGIN ... END block.

while number>0 do
begin
sum := sum + number;
number := number - 2;
end;
For example,

When the condition becomes false, program control passes to the line immediately
following the loop.

Flow Diagram:
Here, key point of the while loop is that the loop might not ever run. When the condition
is tested and the result is false, the loop body will be skipped and the first statement after
the while loop will be executed.

Example:
program whileLoop;
var
a: integer;
begin
a := 10;
while a < 20 do
begin
writeln('value of a: ', a);
a := a + 1;
end;
end.

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

For-do LOOP

A for-do loop is a repetition control structure that allows you to efficiently write a
loop that needs to execute a specific number of times.

Syntax:

The syntax for the for-do loop in Pascal is as follows:

for < variable-name > := < initial_value > to [down to] < final_value > do
S;

Where, the variable-name specifies a variable of ordinal type, called control variable
or index variable; initial_value and final_value values are values that the control
variable can take; and S is the body of the for-do loop that could be a simple statement
or a group of statements.
For example:
for i:= 1 to 10 do writeln(i);

Here is the flow of control in a for-do loop:


· The initial step is executed first, and only once. This step allows you to declare
and initialize any loop control variables.
· Next, the condition is evaluated. If it is true, the body of the loop is executed. If
it is false, the body of the loop does not execute and flow of control jumps to the
next statement just after the for-do loop.
· After the body of the for-do loop executes, the value of the variable in increased
or decreased.
· The condition is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then increment step, and then again
condition). After the condition becomes false, the for-do loop terminates.

Flow Diagram
Example:
program forLoop;
var
a: integer;
begin
for a := 10 to 20 do
begin
writeln('value of a: ', a);
end;
end.

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20

Repeat-Until Loop

Unlike for and while loops, which test the loop condition at the top of the loop, the
repeat ... until loop in Pascal checks its condition at the bottom of the loop.

A repeat ... until loop is similar to a while loop, except that a repeat ... until loop is
guaranteed to execute at least one time.
Syntax:
repeat
S1;
S2;
...
...
Sn;
until condition;

For example,
repeat
sum := sum + number;
number := number - 2;
until number = 0;
Notice that the conditional expression appears at the end of the loop, so the
statement(s) in the loop execute once before the condition is tested.

If the condition is true, the flow of control jumps back up to repeat and the
statement(s) in the loop execute again. This process repeats until the given condition
becomes false.

Flow Diagram:

Example:
program repeatUntilLoop;
var
a: integer;
begin
a := 10;
(* repeat until loop execution *)
repeat
writeln('value of a: ', a);
a := a + 1
until a = 20;
end.
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Nested Loops

Pascal allows using one loop inside another loop. Following section shows few
examples to illustrate the concept.

The syntax for a nested for-do loop statement in Pascal is as follows:


for variable1:=initial_value1 to [downto] final_value1 do
begin
for variable2:=initial_value2 to [downto] final_value2 do
begin
statement(s);
end;
end;

The syntax for a nested while-do loop statement in Pascal is as follows:


while(condition1)do
begin
while(condition2) do
begin
statement(s);
end;
statement(s);
end;

The syntax for a nested repeat ... until loop Pascal is as follows:
repeat
statement(s);
repeat
statement(s);
until(condition2);
until(condition1);

A final note on loop nesting is that you can put any type of loop inside of any other type of
loop. For example, a for loop can be inside a while loop or vice versa.

Example:

The following program uses a nested for loop to find the prime numbers from 2 to
50:

program nestedPrime;
var
i, j:integer;
begin
for i := 2 to 50 do
begin
for j := 2 to i do
if (i mod j)=0 then
break; {* if factor found, not prime *}
if(j = i) then
writeln(i , ' is prime' );
end;
end.

When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
Loop Control Statements:

Loop control statements change execution from its normal sequence. When execution
leaves a scope, all automatic objects that were created in that scope are destroyed.

Pascal supports the following control statements. Click the following links to check
their details.
Control Statements Description
break statement Terminates the loop or case statement and transfers execution to the
statement immediately following the loop or case statement.
continue statement Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
goto statement Transfers control to the labeled statement. Though it is not advised
to use goto statement in your program.

break statement

The break statement in Pascal has the following two usages:

1. When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
2. It can be used to terminate a case in the case statement (covered in the next chapter).

If you are using nested loops (i.e., one loop inside another loop), the break statement
will stop the execution of the innermost loop and start executing the next line of code
after the block.

Syntax:

The syntax for a break statement in Pascal is as follows:

break;
Flow Diagram:

Example:
program exBreak;
var
a: integer;
begin
a := 10;
(* while loop execution *)
while a < 20 do
begin
writeln('value of a: ', a);
a:=a +1;
if( a > 15) then
(* terminate the loop using break statement *)
break;
end;
end

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
continue statement

The continue statement in Pascal works somewhat like the break statement. Instead
of forcing termination, however, continue forces the next iteration of the loop to take
place, skipping any code in between.

For the for-do loop, continue statement causes the conditional test and increment
portions of the loop to execute. For the while-do and repeat...until loops, continue
statement causes the program control to pass to the conditional tests.

Syntax:

The syntax for a continue statement in Pascal is as follows:

continue;

Flow Diagram:
Example:
program exContinue;
var
a: integer;
begin
a := 10;
(* repeat until loop execution *)
repeat
if( a = 15) then
begin
(* skip the iteration *)
a := a + 1;
continue;
end;
writeln('value of a: ', a);
a := a+1;
until ( a = 20 );
end.

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement

A goto statement in Pascal provides an unconditional jump from the goto to a labeled
statement in the same function.

NOTE: Use of goto statement is highly discouraged in any programming language


because it makes difficult to trace the control flow of a program, making the program
hard to understand and hard to modify. Any program that uses a goto can be rewritten
so that it doesn't need the goto.

Syntax:

The syntax for a goto statement in Pascal is as follows:

goto label;
...
...
label: statement;

Here, label must be an unsigned integer label, whose value can be from 1 to 9999.

Flow Diagram:
Example:

The following program illustrates the concept.


program exGoto;
label 1;
var
a : integer;
begin
a := 10;
(* repeat until loop execution *)
1: repeat
if( a = 15) then
begin
(* skip the iteration *)
a := a + 1;
goto 1;
end;
writeln('value of a: ', a);
a:= a +1;
until a = 20;
end.

When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

You might also like