CSC301 UNIT 6a Conditional Statements and Loops
CSC301 UNIT 6a Conditional Statements and Loops
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:
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:
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:
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' );
When the above code is compiled and executed, it produces the following result:
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:
>> 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
program beBitwise;
var
a, b, c: integer;
begin
a := 60; (* 60 = 0011 1100 *)
b := 13; (* 13 = 0000 1101 *)
c := 0;
c := a or b; (* 61 = 0011 1101 *)
writeln('Line 2 - Value of c is ', c );
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; (* 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:
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
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
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:
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
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:
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.
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' );
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
Syntax:
case (expression) of
L1 : S1;
L2: S2;
...
...
Ln: Sn;
end;
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.
Flow Diagram:
Example:
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
The case-else statement uses an else term after the case labels, just like an if-then-else
construct.
Syntax:
case (expression) of
L1 : S1;
L2 : S2;
...
...
Ln: Sn;
else
Sm;
end;
Flow Diagram:
Example:
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:
Syntax:
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:
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 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:
while (condition) do S;
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:
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);
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 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
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:
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:
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.
Syntax:
goto label;
...
...
label: statement;
Here, label must be an unsigned integer label, whose value can be from 1 to 9999.
Flow Diagram:
Example:
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