Control Structures-Selection 1
Program Control Structures - PASCAL
A program is usually not limited to a linear sequence of instructions. During its
process it may repeat code or take decisions. For that purpose, Pascal provides
control structures that serve to specify what has to be done by our program,
when and under which circumstances. Control structures determine how a set of
instructions are executed.
There are Three Control Structures namely:
• Sequence
• Selection
• Looping/Iteration/Repetition
Conditional/Relational/Comparison Operators
To control the program flow, we can use various conditional operators. Basically,
they resemble mathematical operators. Conditional operators are very powerful
tools, they let the program compare data values and then decide what action to
take, whether to execute a program or terminate the program and more. These
operators are shown in Table below
Operator Meaning
= Equal to
> More than
< Less Than
>= More than and equal
<= Less than and equal
<> Not Equal to
Control Structures-Selection 2
Logical Operators
In addition to conditional operators, there are a few logical operators which offer
added power to the Pascal programs. There are shown in Table Below.
Operator Meaning
And Both Conditions must be
true
Or One Condition or other
must be true
Not Negates truth
You can also compare strings with the above operators. However, there are
certain rules to follows: Upper case letters are less than lowercase letters,
"A"<"B"<"C"<"D".......<"Z" and number are less than letters.
Sequence
Statements executed one after another in order. Each statement in the program
is executed once, and they are executed in the same order that they are listed.
Selection/Decision Making
Selection allows the program to make decisions when it processes input from the
user, and control the program flow in the process. Decision making process is an
important part of programming because it can help to solve practical problems
intelligently so that it can provide useful output or feedback to the user.
The selection structure specifies alternate courses of program flow.
Selection Control Statements
a) The single-selection structure (IF…THEN Statement)
This is used where there is only one option to choose. The IF…THEN selection control structure allows a set of statements to be executed if a condition is true only. After the true set of actions is executed, program control resumes with the next statement.
Control Structures-Selection 3
Syntax IF (Conditional Expression) THEN <One or more statements to be executed if condition is true>
If the conditional expression is true, the statements will be executed. If the
conditional expression is false the statements will be bypassed
Example 1
Consider a program which prompts the student to enter the score. Students who
score 80% and above are given Rewards for their Best performance.
Program Rewards (I, O);
{IF…THEN DEMO}
VAR
Score: Integer;
Begin
Write (‘Enter Your Score : ‘);
Readln (Score);
IF (Score >= 80) THEN
Writeln (‘Give REWARD’);
End.
Example 2
Program tests if two positive integers are not divisible another
Program Divisibility (I, O);
VAR
X, Y: Integer;
BEGIN
Writeln (‘Enter Two Numbers: ‘);
Readln (X,Y);
IF (X MOD Y = 0) THEN
Writeln (X, ‘ Is Divisible By ‘,Y);
END.
Control Structures-Selection 4
The double-selection structure (If...Then…Else)
This is used where there are two options to choose. The If-Then-Else statement is a "two-alternative" decision (Actions are taken on both the "If" side and the "Else" side). The IF…THEN…ELSE selection control structure allows one set of statements to be executed if a condition is true and another set of actions to be executed if a condition is false.
After either the true set of actions or the false set of actions is taken, program control resumes with the next statement (the statement that would be placed below the connector in the flowchart above). Syntax If <conditional expression> Then <One or more statements to be executed if condition is true> Else <One or more statements to be executed if condition is false>; If the conditional expression is true, the statements between the keywords Then and Else will be executed (and the statements after the keywords Else will be bypassed). If the conditional expression is false, the statements after the keywords Else will be executed (and the statements between the keywords Then and Else will be bypassed). In any case, program control will resume with the statement following after the If statement.
Control Structures-Selection 5
Example 1
Program Divisibility (I, O);
{IF…THEN…ELSE DEMO}
VAR
X, Y: Integer;
BEGIN
Writeln (‘Enter Two Numbers: ‘);
Readln (X,Y);
IF (X MOD Y = 0) THEN
Writeln (X, ‘ Is Divisible By ‘,Y)
ELSE
Writeln (X, ‘ Is NOT Divisible By ‘,Y);
END.
Example 2
Program Largest_Integer (I, O);
{IF…THEN…ELSE DEMO}
VAR
X, Y: Integer;
BEGIN
Writeln (‘Enter Two Numbers: ‘);
Readln (X,Y);
IF (X >Y) THEN
Writeln (X, ‘ Is Larger Than ‘,Y)
ELSE
Writeln (Y, ‘ Is NOT Divisible By ‘,X);
END.
Control Structures-Selection 6
Example 3
Program Largest (I, O);
{IF…THEN…ELSE DEMO – Largest Number btwn Three Integers}
VAR
X, Y, Z, L: Integer;
BEGIN
Writeln (‘Enter Three Different Numbers: ‘);
Readln (X,Y,Z);
L:= X;
IF (Y>L) THEN
L:= Y;
IF (Z>L) THEN
L:= Z;
Writeln (‘The Largest Integer is ‘,L);
END.
Example 4
Program Minimum (I, O);
{IF…THEN…ELSE DEMO – Minimum Number btwn Three Integers}
VAR
X, Y, Z, Min: Integer;
BEGIN
Writeln (‘Enter Three Different Numbers: ‘);
Readln (X,Y,Z);
Min:= X;
IF (Y<Min) THEN
Min:= Y;
IF (Z<MIN) THEN
Min:= Z;
Writeln (‘The Minimum Integer is ‘,Min);
END.
Control Structures-Selection 7
The multiple-selection structure (Case Statement or Nested If Statement)
When the situation arises where you need to choose between more than two alternatives, an extended form of the selection structure, called the case structure, must be used. A flowcharted example follows:
In Pascal, the Multiple selections can be implemented in one of two ways: with an extended (Nested) block If structure, or with the Case statement structure. Extended (Nested) Block If Statement Format/Syntax: If <conditional expression 1> Then <one or more statements to be executed if condition 1 is true> Else If <conditional expression 2> Then <one or more statements to be executed if condition 2 is true> . . . Else If <conditional expression n> Then <one or more statements to be executed if condition n is true> Else <one or more statements to be executed if none of the above conditions is true>; Note that one or more Else If clauses are "sandwiched" between the first "If" clause and the last "Else" clause. Note also the keyword ElseIf is one word. if "conditional expression 1" is true, perform the statements associated with that condition, then exit to the statement following the End If; if "conditional expression 1" is false, then check "conditional expression 2" - if "conditional expression 2" is true, perform the statements associated with that condition, then exit to the statement following the End If, and so on. Pascal will execute the statements associated with the first true conditional expression it finds and then exit to the statement following the End If. The final
Control Structures-Selection 8
Else statement is often useful to trap errors that may occur when unexpected conditions arise, none of which matches the conditions in the previous If or Else If clauses. Example:
If Avg >= 80 Then Writeln(‘Grade A’) Else If Avg >= 60 Then Writeln(‘Grade B’) Else If Avg = 40 Then Writeln(‘Grade C’) Else If Avg >= 20 Then Writeln(‘Grade D’) Else Writeln(‘Grade E’);
The Case Statement Pascal’s Case is a powerful statement with several options. The format/Syntax is: Case <Test Expression> OF
<expression list 1>: <statement list 1>; <expression list 2>: <statement list 2>;
… Else <statement list n> End; The format above is to be understood as follows: The Case statement specifies an expression to be tested. Each subsequent Case clause specifies an expression(s) that the test expression will be compared to. The first Case clause that contains an expression that matches the test expression will have its associated actions executed, then program control will branch to the statement following End. The final Case Else clause is often useful to trap errors that may occur when an unexpected value of the test expression is present, none of which matches the expression list specified in any of the above Case clauses. Example:
CASE Avg OF 80..100: Writeln(‘Grade A’) 60..79: Writeln(‘Grade B’) 40..59 Writeln(‘Grade C’) 20..39 Writeln(‘Grade D’) 0..19 Writeln(‘Grade E’) Else Writeln(‘Invalid Grade’); End.
Control Structures-Selection 9
The expression list in a "Case statement" can have any of the following formats:
Format Examples
<expression> [, expression, . . . ] 1, 10, 100 "Y", "y"
<expression> .. <expression> 1..9 "A".."C"
(combination of any of the above) 5, 20..29, 43
EXAMPLES
Control Structures-Selection 10
REPETITION/ ITERATION STRUCTURES (LOOPS)
Iteration is the repetition of a statement or block of statements in a program. Loops have as purpose to repeat a statement a certain number of times or while a condition is fulfilled.
Pascal has three iteration statements namely
1. While…Do
2. Repeat…Until
3. For...Do
The while…do loop
It is a pre-conditional looping control structure (i.e. it first checks the conditional expression and starts the execution only if the condition evaluates to TRUE). Therefore A while loop will allow a statement to be repeated zero or more times.
Syntax
While (Conditional Expression) do
Statement; Its functionality is simply to repeat statement while the condition set in expression is true.
For example,
The Repeat…Until loop
It is a post-conditional looping control structure (i.e. it first executes the body of the loop once and then checks the conditional expression. The execution is repeated until the condition evaluates to TRUE). Therefore A Repeat…until loop will allow a statement to be repeated at least once or more times.
Syntax
Repeat
Statement;
Until (Conditional Expression);
Control Structures-Selection 11
Its functionality is exactly the same as the while loop, except that condition in the Repeat-Until loop is evaluated after the execution of statement instead of before, granting at least one execution of statement even if condition is never fulfilled.
For example,
FOR ….Do Loop
A for loop executes a section of code for a fixed number of times. The for loop is used you already
know the number of times a section of code is going to be executed.
Syntax
FOR Loop Control Var := Initial Value TO Final Value DO
Statements;
OR
FOR Loop Control Var := Final Value DOWNTO Initial Value DO
Statements;
Example
Control Structures-Selection 12
PROCEDURES AND FUNCTIONS
PROCEDURES
A procedure is a group of self-contained statements that can be used to perform a
particular activity or a specific task. Procedures are used to break large
programs in smaller, simple and manageable subprograms/subroutines.
A complete program is usually made of many different procedures, each having
been tested, before being used as part of the whole program.
Procedure declaration (Where a procedure is written)
In Pascal, procedures are written after the global constant and variable
declarations of the program and before the body the main program (i.e. before the
executable statements of the main program).
PROGRAM Name/Identifier (I, O);
Global Constants
Type Definitions
Global Variables
PROCEDURE
PROCEDURE
BEGIN
Main program executable statements;
END. {Main Program}
Structure of a procedure
The structure of a Procedure is basically the same as a program.
The first part of a Procedure is the Heading. This is followed by the body of a
procedure. The body of the procedure is enclosed between the RESERVED words
BEGIN and END. A procedure ends with a semicolon after the final end (not full
stop).
Control Structures-Selection 13
Structure
PROCEDURE name/Identifier (List of Formal Parameters); {Procedure Header}
Local Constants Declarations
Local Variables Declarations
BEGIN
Executable statements of procedure
END;
Formal Parameters/Arguments are list of data declarations listed in the
procedure header. Formal parameters are used to pass data to and/or from the
procedure.
Local Variables are variables declared inside a given procedure and can be
accessed or used only in a procedure in which they are declared. These types of
variables are only meaningful inside the procedure. No statements outside the
procedure may reference local variables.
Global Variables are variables declared for the entire program. Global variables
can be utilised anywhere within the program block, whether inside of or external
to the procedure.
Example
Procedure Swap (x, y: Integer); {Procedure Header}
VAR
{Local Variable}
Temp: Integer;
Begin {Body of the Procedure}
Temp: = x;
x: = y;
y: = temp;
writeln(‘Swapped Values’);
writeln(‘X is ‘,x);
writeln(‘Y is ‘,y);
End;
Control Structures-Selection 14
Calling a Procedure
A procedure can be called at a specific place within the main program to use their
functionality. To call a procedure state the name of the procedure and the
parameters (data items) required by the procedure.
Therefore a procedure call may have two parts, the name of the procedure and a
list of data known as the Actual Parameter List
The list of variables or constants after the procedure name is known as actual
parameter.
The number of actual parameter MUST be the same as the number of
corresponding formal parameters
The order of actual parameters and formal parameters must be the same
The data types of the corresponding actual and formal parameters must be the
same.
Example
PROGRAM Swapping (I, O);
VAR
{Global Variables}
a, b: Integer;
Procedure Swap (x, y: Integer); {Procedure Header}
VAR
{Local Variable}
Temp: Integer;
Begin {Body of the Procedure}
Temp: = x;
x: = y;
y: = temp;
writeln (‘Swapped Values’);
writeln (‘X is ‘,x);
writeln (‘Y is ‘,y);
End; {End Procedure}
Control Structures-Selection 15
BEGIN {Main Program}
Writeln (‘Enter Two Numbers to be swapped ‘);
Readln (a, b);
{Procedure Call}
Swap (a, b);
END. (End Main Program}
Procedure to display the largest Integer from three different numbers
Program Largest_Demo (I, O);
{Procedure_Demo – Largest Number btwn Three Integers}
VAR {Global Variables}
X, Y, Z, L: Integer;
Procedure Largest (a, b, c: Integer);
Begin
L:= a;
IF (b>L) THEN
L:= b;
IF (c>L) THEN
L:= c;
Writeln (‘The Largest Integer is ‘,L);
End;
BEGIN
Writeln (‘Enter Three Different Numbers: ‘);
Readln (X,Y,Z);
Largest(X, Y, Z);
END.
Control Structures-Selection 16
FUNCTIONS
A Function is a group of self-contained statements that can be used to perform a
particular activity or a specific task similar to a procedure. It is used to return a
value to the procedure or program which calls it.
Characteristics of a FUNCTION
1. It begins with the keyword FUNCTION
2. It structure is similar to the procedure
3. It returns some value (simple data types) when called
4. It is used on the right side of an expression
Structure of a FUNCTION
The structure of a function is basically the same as a procedure.
The first part of a FUNCTION is the Heading. This is followed by the body of a
FUNCTION. The body of the FUNCTION is enclosed between the RESERVED
words BEGIN and END. A FUNCTION ends with a semicolon after the final end
(not full stop).
Somewhere inside the code associated with the function, a value is assigned to
the function name.
Structure
FUNCTION name/Identifier (List of Formal Parameters): Return DATA Type;
{Function Header}
Local Constants Declarations
Local Variables Declarations
BEGIN
Executable statements of the function;
Function Name: = return value;
END;
Control Structures-Selection 17
Example – Function to Calculate simple Interest
Function Interest (P: longint; R: Real; T: Integer): Real; {Function Header}
VAR
{Local Variable}
Result: Real;
Begin {Body of the Function}
Result: =(P*R*T)/100;
Interest: = Result; (*Function Name assigned a value*)
End;
CALLING A FUNCTION
User defined functions are called the same way as standard functions. To call
any function in Pascal, specify the Function name and the arguments.
During the function call, the program provides the function with one or more
arguments/parameters and the function returns a single value.
Example
PROGRAM Function_Demo (I, O);
VAR
{Global Variables}
Principal: longint;
Time: Integer;
Rate, Amount, Intr: Real;
Function Interest (P: longint; R: Real; T: Integer): Real; {Function Header}
VAR
{Local Variable}
Result: longInt;
Begin {Body of the Function}
Result: =(P*R*T)/100;
Interest: = Result; (*Function Name assigned a value*)
End;
BEGIN
Write (‘Enter the Principal Amount Invested ‘); Readln (Principal);
Write (‘Enter the rate of investment ‘); Readln (Rate);
Control Structures-Selection 18
Write (‘Enter the years the of the investment will take ‘); Readln (Time);
Intr: = interest (Principal, Rate, Time); (*Function call*)
Amount: = Principal + Intr;
Write (‘The Accumulated Interest is ‘,intr: 8:2);
Write (‘The Total Amount is ‘, Amount: 10:2);
END.
PARAMETER PASSING
Parameters can either be passed by value or by reference.
Pass by Value (Value Parameters)
This method copies the value of the actual parameter into the formal parameter of
the called procedure/function.
The called procedure/function does not have access to the actual parameter
instead it uses a copy of the actual parameter.
Example showing the declaration of a Value Parameter
Procedure Largest (a, b, c: Integer);
Note: a, b c are declared as value parameters
Pass by Reference (Reference/Variable Parameters)
This method copies the address of the actual parameter into the formal parameter
of the called procedure/function.
The called procedure/function has direct access to the actual parameter. This
method is used when there is a need to change the values of the variables using a
function/procedure.
Example showing the declaration of a Reference Parameter
Procedure Largest (VAR a: real; b: integer; VAR c: Integer);
Note: a and c are declared as Reference/Variable parameters
while b is a Value parameter
STANDARD FUNCTIONS
Pascal contains a number of standard functions used with various simple data
types. These functions also called built-in functions. Some common standard
functions provided in Pascal are:
ABS – The ABSolute Function returns the absolute value either an integer or real
e.g. ABS (-34) returns 31
Control Structures-Selection 19
COS – The COSine Function returns the cosine value, in radians, of an argument
e.g. COS (0) returns 1.0
SIN – The Sine Function returns the sine value, in radians, of an argument e.g.
SIN (60) returns 0.8660
LN – The logarithm Function returns the natural log of a number greater than
zero
EXP – The Exponential Function calculates e raised to power of a number, e.g.
EXP (10) returns e (natural log) to power of 10.
There is no function in Pascal to calculate expressions such as 23, which would
be expressed as 23 = 2*2*2
These are calculated by using the formula an = exp (n*ln (a))
ODD – The odd function determines when a specified number is odd or even,
returning true when the number is odd, false when it is not.
SQR – The square function returns the square of a number (i.e. the argument
multiplied by itself. E.g. SQR (2) returns 4
SQRT – This function returns the square root of a number e.g. SQRT (25) returns
5
TRUNC – The function returns the whole number of a real number without
decimals. E.g. TRUNC (56.99) returns 56, TRUNC (-36.89) returns -36
CHR – Returns the character associated with the ASCII value being asked. E.g.
CHR (65) Returns A
ORD – Returns the the ASCII value associated with character being asked (i.e. it
is the reverse of the CHR function). E.g. ORD (‘A’) Returns 65, ORD (‘C’) Returns
67
Note: Ordinal Data types are those types that have known set values. Each value
which follows in the set is one greater than the previous. Characters and integers
are thus ordinal data types.
SUCC – The successor function returns the next value or symbol in the set e.g.
succ (‘d’) returns e,
PRED – The predecessor function returns the previous value or symbol in the set
e.g. pred (‘d’) returns c,
Control Structures-Selection 20
STRUCTURED DATA TYPES (DATA STRUCTURES)
Data structure is a collection of related information that is used to store different
variables under a single name. All data structures have associated algorithms to
manage the data structure while maintaining its properties. Common Structured
data types include Arrays, Records, Files etc.
ARRAYS
An array is a collection of data items of similar data type. It’s a composite object;
it is composed of several elements with independent values all of which have the
same type.
The independent values are called the elements of an array and they are stored
in separate cells. Each cell of an array is assigned an index or a subscript.
An array can be:
1. Single Dimension Array or
2. Multidimensional Array
SINGLE DIMENSIONAL ARRAY
A single dimensional array stores data items in form of rows
Representation of a one-dimensional array
An array is first declared in the program before it can be used. The array
declaration specifies the name of the array, data type and the size of the array.
The size of the array specifies to the number of data items/elements that array
contains.
NOTE:
1. The contents of the array MUST be of the same data type. (i.e. an array can
contain all integers, or all Reals, or all characters or all strings, but not a
mixture of each type.
2. Each item in the array is stored in a separate cell. (E.g. if an array
contained five integers each integer would occupy a single cell.
3. Each cell has a unique index/subscript showing its position in the array.
Numbers
1 2 3 4 5 Index
Control Structures-Selection 21
4. The array is given only ONE name/identifier, irrespective of items it
contains.
5. An array MUST be declared like any other variable before it can be used.
DECLARING A ONE DIMENSION ARRAY
Syntax
VAR
Array Name: ARRAY [size] OF Data type;
OR
TYPE
Type Name = ARRAY [size] OF Data Type;
VAR
Array Name: Type Name
Example
VAR
Result: ARRAY [1..10] OF Integer;
Scores: ARRAY [1..7] OF Real;
Grades: ARRAY [1..5] OF Char;
Names: ARRAY [1..20] OF String;
ACCESSING ELEMENTS/DATA ITEMS OF AN ARRAY
Access to an item within a cell of an array, the name of the array followed by the
position/index/subscript number, contained in square brackets is used.
Syntax
Array Name [index]
Example
Result [1] – Specifies the first element of the array, result
Scores [2] – Specifies the second element of the array, scores
Grades [3] – Specifies the third element of the array, Grades
Names [18] – Specifies the 18th element of the array, Names
Control Structures-Selection 22
STORING/ASSIGNING A VALUE TO ELEMENTS OF AN ARRAY
To store a value in a given cell/element of an array the assignment statement is
used.
Syntax
Array Name [index] := Value;
Example
Result [1]:= 78; - Stores the number 78 in the first cell
Scores [2]:= 56.66; -Stores the number 56.66 in the second cell
Grades [3]:= ‘A’; -Stores a character ‘A’ in the Third cell
Names [18]:=’William’; --Stores the Name ‘William’ in the 18th cell
INPUT AND OUTPUT OF DATA IN AN ARRAY
In Pascal, the Read/Readln statement is used to read data from the keyboard and
store it into the appropriate array cell just like the scalar data types.
The Write/Writeln statement is used to display the contents of an array element
to the screen.
Input of data in Array
Readln (Result [1]);
Readln (Scores [2]);
Readln (Grades [3]);
Displaying the Contents of an Array (Output of data)
Writeln (Result [1]);
Writeln (Scores [2]);
Control Structures-Selection 23
Example
Program Array_Demo (I, O);
{Program to assign numbers directly to the cells of an array and display the
contents of these cells}
VAR
Scores: Array [1..5] Of Integer;
BEGIN
{Direct Assignment of Numbers to cells of the Array}
Scores [1]: = 45;
Scores [2]: = 66;
Scores [3]: = 99;
Scores [4]: = -245;
Scores [5]: = 13;
{Displaying the contents of these cells}
Writeln (‘Contents of the Array’);
Writeln (‘Cell 1 ’, Scores [1]:4);
Writeln (‘Cell 2 ’, Scores [2]:4);
Writeln (‘Cell 3 ’, Scores [3]:4);
Writeln (‘Cell 4 ’, Scores [4]:4);
Writeln (‘Cell 5 ’, Scores [5]:4);
END. {ARRAY DEMO}
Control Structures-Selection 24
USING THE FOR LOOP TO ACCESS ARRAY ELEMENTS
The For Loop is usually used to easily access the cells/elements of the array. The
For loop reduces the amount of coding. The for loop control variable is used to
represent the index/subscript of the array.
Instead of explicitly coding Scores [1], Scores [2]… Scores [5] it is easier to use
Scores [Index], and embed this statement in for…do loop changing the value of
the index from 1 to 5.
Example
Program Array_Demo (I, O);
{Program to Input numbers into a one-dimension Array and display the contents
of these cells}
(*Using The FOR LOOP*)
VAR
Scores: Array [1..5] Of Integer;
Index: Integer;
BEGIN
{Input Numbers to cells of the Array from the Keyboard}
Writeln (‘Enter Five Integers, one per line’);
FOR Index:=1 TO 5 DO
Readln (Scores [Index]);
{Display the contents of these cells}
Writeln (‘Contents of the Array’);
FOR Index:=1 TO 5 DO
Writeln (‘Cell ‘, Index, Scores [Index]:4);
END. {ARRAY DEMO}
Control Structures-Selection 25
ARRAY OF CHARACTERS
A variable of string data type is represented as an array of characters, and the
maximum size of this array in Turbo Pascal is 255 Characters.
In Turbo Pascal, the size of the string is stored by the system as a character in
cell 0 of the array. The length of the string can be obtained by taking the ordinal
value of the character stored in cell 0. For example in a string variable Message,
ORD(Message[0])- gives the size of the variable Message (i.e. Number of characters
stored in the variable Message).
The declaration of an Array of characters is not the same as the declaration of a
string. The size of an array of characters is FIXED at the time it is declared.
For Example
VAR
Alphabet: ARRAY [1..26] OF Char;
Defines a fixed-length array that can accommodate 26 characters only. Whereas
the Declaration
VAR
Message: String;
Defines a Variable-length array that can accommodate up to 255 characters.
Example
Program to test a word for being a palindrome – that is a word spelt the same
backwards and forwards e.g. RADAR, MADAM, DAD, are palindromes.
Program Palindrome (I, O);
VAR
Word: String
Index1, Index2: Integer;
Match: Boolean;
Begin
{Input The Word}
Writeln (‘Enter The Word’); Readln (Word);
Index1: =1;
Index2: =Ord(word[0]); {Returns the Length of the Word}
Match: = True;
Control Structures-Selection 26
{Test For Palindrome}
While (Index1<=Index2) AND (Match) DO
Begin
If (Word [index1] = Word [index2]) Then
Begin
Index1: =Index1 +1;
Index2: =index2 – 1;
End
Else
Match: =False; {End If}
End; {End While}
{Output The Result}
If Match Then
Writeln (Word, ‘ Is a Palindrome’)
Else
Writeln (Word, ‘ Is NOT a Palindrome’);
END. {Palindrome}
Program to count Vowels in a given sentence.
Program Vowel_Count (I, O);
VAR
Word: String
Index, Length, VCount: Integer;
Begin
{Input The Sentence}
Writeln (‘Enter The Sentence, Terminate with the enter key’); Readln (Word);
Length: =Ord(word[0]); {Returns the Length of the Word}
Vcount: =0;
{Vowel Count}
For Index:=1 TO Length DO
Begin
Case (Word[index]) OF
‘a’, ‘e’, ‘i’, ‘o’, ‘u’: Vcount: = Vcount + 1;
‘A’, ‘E’, ‘I’, ‘O’, ‘U’: Vcount: = Vcount + 1;
Control Structures-Selection 27
End;
End;
{Output The Result}
Writeln (‘The Number of vowels Is ’,Vcount:5)
END. {Vowel Count}
TWO DIMENSIONAL ARRAYS
A Two dimensional array stores data items in form of rows and columns
Representation of a Two-Dimensional array
Columns
DECLARING A TWO DIMENSION ARRAY
Syntax
VAR
Array Name: ARRAY [Row size, Column Size] OF Data type;
OR
TYPE
Type Name = ARRAY [Row size, Column Size] OF Data Type;
VAR
Array Name: Type Name
Example
VAR
Result: ARRAY [1..10, 1..5] OF Integer;
Scores: ARRAY [1..7, 1..3] OF Real;
Grades: ARRAY [1..5, 1..2] OF Char;
Names: ARRAY [1..20, 1..4] OF String;
Rows
Control Structures-Selection 28
ACCESSING ELEMENTS/DATA ITEMS OF AN ARRAY
Access to an item within a cell of an array, the name of the array followed by the
Row index/subscript and column index/subscript number, contained in square
brackets is used.
Syntax
Array Name [Row index, Column Index]
Example
Result [1, 1] – Specifies the element on the first row, first column of the array,
result (i.e. cell 1 on row 1)
Scores [2, 1] – Specifies the element on the second row, first column of the array,
Scores (i.e. cell 1 on row 2)
Grades [3, 2] – Specifies the element on the third row, second column of the
array, Grades (i.e. cell 2 on row 2)
STORING/ASSIGNING A VALUE TO ELEMENTS OF AN ARRAY
To store a value in a given cell/element of an array the assignment statement is
used.
Syntax
Array Name [Row index, Column Index] := Value;
Example
Result [1, 1]:= 78; - Stores the number 78 in the first cell of the first row
Scores [2, 2]:= 56.66; -Stores the number 56.66 in the second cell of the second
row
Control Structures-Selection 29
INPUT AND OUTPUT OF DATA IN AN ARRAY
In Pascal, the Read/Readln statement is used to read data from the keyboard and
store it into the appropriate array cell just like the scalar data types.
The Write/Writeln statement is used to display the contents of an array element
to the screen.
Input of data in Array
Readln (Result [1, 1]);
Readln (Scores [2, 2]);
Readln (Grades [3, 1]);
Displays the Contents of an Array (Output of data)
Writeln (Result [1, 1]);
Writeln (Scores [2, 2]);
EXAMPLE
Write a Pascal program to produce the following multiplication table
1 2 3 4 5
2 4 6 8 20
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
6 12 18 24 30
Program 2_D_Array_Demo (I, O); VAR Table: ARRAY [1..6, 1..5] OF Integer; Y, r, c: Integer; Begin Writeln (‘The Multiplication Table’); For r: = 1 To 6 Do Begin For c: = 1 To 5 Do Begin y: = r*c; write (y:4); table [r, c]:=y; End; Writeln; End; End.
Control Structures-Selection 30
Example 2; The figure below shows a typical data structure. Use it to answer the question that follows
4 6 2 0
5 3 8 7
9 0 11 13
Write a Pascal program statement to: a) Declare the data structure b) Initialize the data structure c) State the limitation of this structure
Solution Declaration of a 2-D array VAR Numbers: ARRAY [1..3, 1..4] OF Integer; Initialization/direct assignment of values to elements of the ARRAY Begin
Numbers [1, 1]: = 4; Numbers [1, 2]: = 6; Numbers [1, 3]: = 2; Numbers [1, 4]: = 0; Numbers [2, 1]: = 5; Numbers [2, 2]: = 3; Numbers [2, 3]: = 8; Numbers [2, 4]: = 7; Numbers [3, 1]: = 9; Numbers [3, 2]: = 0; Numbers [3, 3]: = 11; Numbers [3, 4]: = 13;
End; The main limitation of this data structure is that its static. SEARCHING AND SORTING SORTING Sorting is the process of arranging a collection of data in order. Sorting can also be defined as the process of arranging data items in a specified order. For example, arranging names of students in a class in an alphabetical order. The numerical data can be arranged in increasing or decreasing order and character data can be arranged alphabetically. SORTING TECHNIQUES Sorting is the process of arranging data items in a specified order. For example, arranging names of students in a class in an alphabetical order. The basic operation in Sorting techniques is to compare the data items of the array with other data items of the array and swap the position of these data items of the array in a specified order i.e. ascending or descending. Sorting techniques can be implemented using any programming language, such as Pascal.
Control Structures-Selection 31
The following sorting techniques can used to arrange data items in a specified order:
a) Bubble Sort b) Insertion Sort c) Selection Sort d) Quick Sort e) Shell Sort etc
BUBBLE SORT This is the simplest sorting algorithm. The bubble sort is a sorting technique that keeps comparing the two adjacent data items of an array and swaps them in a specified order repeatedly until the whole array has been sorted. How It Works This technique starts with comparing the first two data items of the array and swaps them if they are not in a specified order. After sorting the first two data items of the array, the next two data items are compared and swapped, if they are not in order. This process continues until all the data items of the array are compared or the end of the array is reached. This process of comparing consecutive data items continues till the whole array is sorted in a specified order. Example 1 Program Bubble_Sort (I, O); VAR A: ARRAY [1..6] OF Integer; Temp, j, i: Integer; Begin Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); (*Bubble Sort- Ascending*) For i:= 1 To 6 Do Begin For j: = 1 To 5 Do Begin If (A[j] > A [j+1]) Then Begin Temp: = A[j]; A [j]: = A [j+1]; A [j+1]: = Temp; End; End; End; Writeln (‘The Sorted List’); For i: = 1 To 6 Do Writeln (A [i]); End.
Control Structures-Selection 32
Using a Procedure to Sort Example 1 Program Bubble_Sort (I, O); Type List = ARRAY [1..6] OF Integer VAR A: List; j, i: Integer; Procedure Bubble_Sort (data: List); Var Temp:integer; Begin (*Bubble Sort- Ascending*) For i:= 1 To 6 Do Begin For j: = 1 To 5 Do Begin If (Data [j] > Data [j+1]) Then Begin Temp: = Data [j]; Data [j]: = Data [j+1]; Data [j+1]: = Temp; End; End; End;
Writeln (‘The Sorted List’); For i: = 1 To 6 Do Writeln (Data [i]); End; Begin Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); Bubble_Sort; (*Procedure Call*) End. INSERTION SORT This is simple but inefficient sorting algorithm. The Insertion sort is a sorting technique that picks a data item of an array and then inserts it in the correct position in the array. In insertion sort, an array is divided into two sub-arrays. The first keeps only the sorted data items and the second sub-array keeps remaining unsorted data items. The data item is moved from the second sub-array to the first sub-array until the second sub-array is empty and the first sub-array contain the sorted data items. How It Works This technique starts with selecting the first data item of the array from the unsorted list and then places it in the other (sorted) list. The data items are
Control Structures-Selection 33
sequentially selected from the unsorted list and placed at the appropriate position in the other (sorted) list. This process continues until all the data items of the array are sorted in a specified order. Example 1 Program Selection_Sort (I, O); VAR A: ARRAY [1..6] OF Integer; Temp, key, j, i: Integer; Begin Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); (*Insertion Sort- Ascending*) For k: = 1 To 6 Do Begin For i: = 2 To 6 Do Begin For j: = 1 To i-1 Do Begin If (A[j] > A [j+1]) Then Begin Temp: = A[j]; A [j]: = A [j+1]; A [j+1]: = Temp; End; End; End; End; Writeln (‘The Sorted List’); For i: = 1 To 6 Do Writeln (A [i]); End. SELECTION SORT Selection sort is a sorting technique that selects a data item and stores it in the appropriate position of the array, until all the data items are arranged. In the selection sort technique, the smallest data item in the array is selected and stored in the first position. The second smallest data item of the array is selected and stored in the second position of the array. This process of selecting and replacing continues until all the data items of the array are arranged in a sorted order.
Control Structures-Selection 34
Example 1 Program Selection_Sort (I, O); VAR A: ARRAY [1..6] OF Integer; Temp, Smallest, Loc, j, i: Integer; Begin Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); (*Selection Sort- Ascending*) For i: = 1 To 6 Do Begin Smallest: = A [i]; For j: = i To 5 Do Begin If (Smallest > A [j+1]) Then Begin Smallest: = A [j+1]; Loc: = j+1; End End; Temp: = A[i]; A [i]: = Smallest; A [Loc]: = Temp; End; Writeln (‘The Sorted List’); For i: = 1 To 6 Do Writeln (A [i]); End. SEARCHING Searching is the process of finding the location of some desired data in a collection of data items, such as an array. If the data item that you want to search matches with any data item of the array, the search returns the location of the data item that matches. Otherwise, the search fails. There are two searching techniques namely:
1. Linear/Sequential Search 2. Binary Search
LINEAR/SEQUENTIAL SEARCH In linear search, the data item to be searched is compared with each element of the array, starting from the beginning until the data item is found. In linear search, a data item is compared with each data item of the array one by one until you find the location of the desired data item in the array or the end of the array is reached. If the desired data item is found, this search returns the location of the desired item otherwise the search has failed.
Control Structures-Selection 35
Example Program shows how to search a data item using Linear Search E.g. An array A has the following elements (50, 40, 75, 55, 90, 45). Write a Pascal program that will search the data item 55. Program Linear_Search (I, O); VAR A: ARRAY [1..6] OF Integer; Item, i, Location: Integer; Found: Boolean; Begin Found: = False; Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); Writeln (‘Enter the Data Item to be Searched ‘); Readln (item); For i:= 1 To 6 Do Begin If (A[i] = item) Then (*Matching the Data with the Array data*) Begin Location: =i; Found: = True; End; End; If Found Then Writeln (‘The DataItem is Found at Position : ‘, Location) Else Writeln (‘The Data item is NOT Found’); End. Example 2 Passing an array to a Function/Procedure Program Linear_Search (I, O); TYPE ArrayList = ARRAY [1..6] OF Integer; VAR A: ArrayList; Item, i, Location: Integer; Found: Boolean; Function Linear (y: ArrayList; x: Integer): Integer; Begin For i:= 1 To 6 Do Begin If (y[i] = x) Then (*Matching the Data with the Array data*) Begin Linear: =i;
Control Structures-Selection 36
Found: = True; End; End; End; {Linear Function} Begin {Main Program} Found: = False; Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); Writeln (‘Enter the Data Item to be Searched ‘); Readln (Item); Location: = Linear (A, Item); {Function Call, Passing the array and the item to be searched} If Found Then Writeln (‘The DataItem is Found at Position : ‘, Location) Else Writeln (‘The Data item is NOT Found’); End. BINARY SEARCH The Binary search uses the “divide and conquer” strategy. It repeatedly divides the array into two pieces and then searches the piece that could contain the target value. It can only work if the array is already sorted either in ascending order or in descending order. HOW IT WORKS The data item to be searched is compared with the middle data item of the array. If it is not the target (i.e. does not match with the middle data item), Then comparison decides which part of the array contains the desired data item, it determines whether the searched data item is either in the Upper Half (i.e. Larger then the middle data item )or Lower Half (i.e. Smaller then the middle data item ) Now again compare the desired data item with the middle data item of the Upper or Lower half. This process continues until the desired data item is found or no data item is left to compare.
Control Structures-Selection 37
Example Program shows how to search a data item using Binary Search E.g. An array A has the following elements (50, 40, 75, 55, 90, 45). Write a Pascal program that will search the data item 55. Program Binary_Search (I, O); VAR A: ARRAY [1..6] OF Integer; Item, Left, Right, Mid, Location: Integer; Found: Boolean; Begin Found: = False; Writeln (‘Enter the six Array Elements ‘); For i: = 1 To 6 Do {Loop to enter array elements from the keyboard} Readln (A [i]); Writeln (‘Enter the Data Item to be Searched ‘); Readln (item); Left: = 1; Right: = 6;
While (Left <= Right) AND (Found = False)Do Begin Mid: = (Left + Right) Div 2; If (A [Mid] = item) Then (*Matching the Data with the Array data*) Begin Location: = Mid; Found: = True; End Else If (item > A [Mid]) Then L: = Mid + 1 Else Right: = Mid – 1; End; If Found Then Writeln (‘The DataItem is Found at Position : ‘, Location) Else Writeln (‘The Data item is NOT Found’); End.