CSC 102: INTRODUCTION TO ALGORITHM
TECHNIQUES
3
Virtual Classroom Etiquette
• Be aware of your background
• Sit at a table or desk - Your virtual meeting is the same as attending class
• Utilize the mute button
• Be present - Being present is more than just clicking “Join Meeting.”
• Don’t multitask - It may be very tempting because your computer is
already open
• Use the chat
• Be careful not to interrupt
• Embrace silence
• Do not violate these rules.
© 2003 Prentice Hall, Inc. All rights reserved.
4
COURSE OUTLINES
Module 1
• Problem Solving Strategies
• What is a Problem?
• PROBLEM SOLVING STAGES
• Human versus Computers in Solving Problem
© 2003 Prentice Hall, Inc. All rights reserved.
5
COURSE OUTLINES (Continued)
• Module 2 : Problem Solving Process in Computing
• Problem Solving Process in Computing using
• Algorithm
• Flowcharts
• Pseudo Codes
• Module 3: Roles of algorithm in problem solving process
• Roles of algorithm in problem solving process
• Implementation strategies, concepts and properties of algorithm
© 2003 Prentice Hall, Inc. All rights reserved.
6
COURSE OUTLINES (Continued)
Module 4: Introduction to C • Control Flow Constructs
language part 1 • Decisions
▪ Definition and introduction ✓ IF statement
to: ✓ Nested-IF statements
✓ Variables
✓ Switch Statements
✓ Operators
✓ Expressions • Loops
✓ Statements ✓ FOR- loop statements
▪ Definition and introduction ✓ WHILE-Loop Statements
to: ✓ DO-WHILE Loop Statements
✓ Compiler
✓ Keywords
✓ Header files
© 2003 Prentice Hall, Inc. All rights reserved.
7
COURSE OUTLINES (Continued)
• Module 5: Introduction to C language part 2
• Functions
• Introduction to Arrays
• Introduction to String and String Processing
• Introduction to searching and sorting concepts:
• Structures
© 2003 Prentice Hall, Inc. All rights reserved.
8
PROBLEM SOLVING
INTRODUCTION
• Can you think of a day in your life which goes without problem
solving?
• In our life we are bound to solve problems.
• In our day to day activity such as purchasing something from a
general store and making payments, depositing fee in school, or
withdrawing money from bank account.
• All these activities involve some kind of problem solving
© 2003 Prentice Hall, Inc. All rights reserved.
9
• To make it clearer, let us see some other examples.
• Example1: If you are watching a news channel on your TV and you
want to change it to a sports channel, you need to do something i.e.
move to that channel by pressing that channel number on your
remote. This is a kind of problem solving.
• Example 2: Some students in a class are planning to go on a picnic,
they all decided to share the expenses among themselves. So
calculating total expenses and the amount an individual have to give
for picnic is also a kind of problem solving.
© 2003 Prentice Hall, Inc. All rights reserved.
10
What is aorProblem?
• A problem is defined as the objective the specific output that we
want to attain; through a sequence of steps and activities and,
specific input.
• Consider the following problem:
• The problem is: Baking a cake according to certain specifications,
➢ inputs available are the ingredients (such as eggs, flour, milk
…etc.),
➢ then followed by activities or procedures that should be done
sequentially, taking into consideration that any mistake happens
by doing any procedure before the other, results in an unsuitable and
undesirable cake.
© 2003 Prentice Hall, Inc. All rights reserved.
11
First Problem DefinitionPROBLEM SOLVING STAGES
• Problem definition implies the identification of required outputs,
available inputs and, arithmetic and logical operations to be
executed.
• Second: Performing step-by-step instructions (Algorithm) to
solve a Problem
• After identifying and analysing the problem, outputs and, inputs; a
plan in the form of a series of successive steps is made, which is
called an (Algorithm),
Algorithm is defined as a group of logically arranged procedures to be
executed to attain a goal or precise output, out of specific inputs
© 2003 Prentice Hall, Inc. All rights reserved.
12
• Program Design
• Having drawn a Flowchart/ Algorithm to solve the problem, we have
to translate this flowchart/Algorithm into one of the programming
languages.
• Fourth: Program Testing
• During writing of program we may unintentionally make some
mistakes; e.g. writing a minus sign (-) instead of (+). We can’t detect
errors unless we begin entering data to the program with previously
known results; to compare the results of the current program to those
of the well-known results; therefore we check the errors and debug
them
© 2003 Prentice Hall, Inc. All rights reserved.
13
• Fifth: Program Documentation
• The documentation is beneficial when more than one person
participate in writing or modifying the program
© 2003 Prentice Hall, Inc. All rights reserved.
14
• People either
Human versus
converge inComputers in Solving
their thinking to solveproblem
a problem or they
diverge in their thinking to solve a problem—or they do both
• Convergent vs. Divergent Thinking: Each stage of the problem-
solving process is associated with two fundamental cognitive
operations, namely divergent thinking and convergent thinking.
• The divergent thinking operation involves searching for ideas and
increasing one’s options through elaboration of the problem,
redefinition of the problem, and by exploring, connecting, and/or
combining potential ideas and solutions
© 2003 Prentice Hall, Inc. All rights reserved.
15
• In contrast, the convergent thinking operation involves evaluating
ideas and narrowing or reducing one’s options through the
imposition of value judgments, exploiting the information available
about the ideas, and then prioritizing and selecting
• Exploitation vs. Exploration
• Exploration is about searching for new ideas both inside and outside
the paradigm.
• whereas Exploitation is about taking advantage of an idea within the
paradigm and perfecting it
© 2003 Prentice Hall, Inc. All rights reserved.
16
• Some business problems require mostly exploitation, while others
require mostly exploration, but all problems require some mixture of
the two.
• Computers solve problems using Algorithm. We’ll talk about
algorithms in the next module
© 2003 Prentice Hall, Inc. All rights reserved.
17
ALGORITHM
• An algorithm is a well-defined computational procedure consisting
of a set of instructions that takes some value or set of values, as
input, and produces some value or set of values, as output
OR
• An algorithm is a procedure consisting of a finite set of steps which
specify a finite sequence of operations that provides the solution to
a problem.
• In other word, an algorithm is a procedure that accepts data,
manipulate them following the prescribed steps, so as to eventually
fill the required unknown with the desired value(s).
© 2003 Prentice Hall, Inc. All rights reserved.
18
Why study an Algorithms?
• Computer scientists learn by experience. We learn by seeing others
solve problems and by solving problems by ourselves
• Algorithms are often quite different from one another
• Consider the example of sqrt. It is entirely possible that there are
many different ways to implement the details to compute the square
root function
• As we study algorithms, we can learn analysis techniques that allow
us to compare and contrast solutions based solely on their own
characteristics, not the characteristics of the program or computer
© 2003used [Link]
Prentice Hall, All rights reserved. them
19
Algorithm and Program
What is the difference between an Algorithm and a Program?
• Algorithm is meant in general to be performed by a human while
the computer performs a program.
• Algorithm is the mathematical step-by-step procedure while a
Program is the implementation of the algorithm in a particular
programming language
• Find out more differences
© 2003 Prentice Hall, Inc. All rights reserved.
20
Properties of an Algorithm
• Finiteness: An algorithm must always terminate after a finite number
of steps..
• Definiteness: Each step of an algorithm must be precisely defined. It
is done by well thought actions to be performed at each step of the
algorithm. Also the actions are defined unambiguously for each
activity in the algorithm.
Effectiveness: This means that an algorithm must provide the correct
answer to the problem.
Generality. This means that it must solve every instance of the
problem. For example, a program that computes the area of a
rectangle should work on all possible dimensions of the rectangle.
© 2003 Prentice Hall, Inc. All rights reserved.
21
• Input: Any operation you perform need some beginning
value/quantities associated with different activities in the operation.
So the value/quantities are given to the algorithm before it begins.
• Output: An algorithm must terminate, the result may be obtained at
different stages of the algorithm.
© 2003 Prentice Hall, Inc. All rights reserved.
22
Example
• Design an algorithm to add these test scores: 26, 49, 98, 87, 62, 75
and obtain the Average score
[Link]
2. Sum = 0
3. Input 26, 49, 98, 87, 62, 75
4. Sum = 26+49+98+87+62+75
5. Average = Sum/6
6. Output Average
7. Stop
© 2003 Prentice Hall, Inc. All rights reserved.
23
• Problem 1: Find the area of a Circle of radius r.
ALGORITHM
Step 1: Start
Step 2: Read\Input the Radius
Step 3: Area PI * Sqr(r) // Calculation of area
Step 4: Print Area
Step 5: Stop
© 2003 Prentice Hall, Inc. All rights reserved.
24
• Problem2: Write an algorithm to read two numbers and find their
sum. Inputs to the algorithm:
• Algorithm
• Step 1: Start
• Step 2: Read\Input the first num1
• Step 3: Read\Input the second num2
• Step 4: sum num1 + num2
• Step 5: Print Sum
• Step 6: Stop
© 2003 Prentice Hall, Inc. All rights reserved.
25
Algorithm Analysis
• We can have three cases to analyse an algorithm
1) Worst Case
2) Average Case
3) Best Case
• Worst Case Analysis (Usually Done)
• In the worst case analysis, we calculate upper bound on running time
of an algorithm.
• We must know the case that causes maximum number of operations
to be executed. For Linear Search, the worst case happens when the
element to be searched (x in the above code) is not present in the
array
© 2003 Prentice Hall, Inc. All rights reserved.
26
• Average Case Analysis (Sometimes done)
• In average case analysis, we take all possible inputs and calculate
computing time for all of the inputs. Sum all the calculated values
and divide the sum by total number of inputs. We must know (or
predict) distribution of cases. For the linear search problem, let us
assume that all cases are uniformly distributed (including the case of
x not being present in array).
© 2003 Prentice Hall, Inc. All rights reserved.
27
• Best Case Analysis (Bogus)
• In the best case analysis, we calculate lower bound on running time
of an algorithm. We must know the case that causes minimum
number of operations to be executed. In the linear search problem,
the best case occurs when x is present at the first location. The
number of operations in the best case is constant (not dependent on
n). So time complexity in the best case would be Θ(1)
© 2003 Prentice Hall, Inc. All rights reserved.
28
Essential Elements of a Good Representation
Show the Logic.
Your algorithm representation should focus on the logic of the
problem, and not the logic of the eventual implementation.
2. Reveal the Flow
Most problems, especially if they are intended to be solved with the
aid of a computer program, involve flow control.
3. Be Expandable and Collapsible
Our algorithm representation should be flexible and allow us to
readily collapse it so as to show less detail and focus on the more
abstract elements of the algorithm or to expand it so as to get as
detailed as necessary in order to actually implement the solution.
© 2003 Prentice Hall, Inc. All rights reserved.
29
4. Aid in Implementation
At the end of the day, the goal is usually to actually implement a solution to the
problem being solved. If our method of representing our algorithm does not lend
itself to an orderly implementation of that algorithm, then our method is
seriously flawed. Conversely, if our method of representation lends itself to a
systematic implementation of the algorithm, then our method is extremely
useful
5. Implementation Independence
From this point forward, we will restrict the discussion to algorithms that are intended for eventual
implementation using a computer program - but the concepts described can be readily
generalized to any type of implementation and you should read them with the intent of grasping
those generalized concepts.
© 2003 Prentice Hall, Inc. All rights reserved.
30
Tools for representing Algorithm
• There are two tools for representing an Algorithm
• Pseudocode
• Flowchart
➢ Pseudocode: Pseudocode is one of the tools that can be used to
write a preliminary plan that can be developed into a computer
program.
➢ Pseudocode is a generic way of describing an algorithm without use
of any specific programming language syntax.
➢ It is, as the name suggests, pseudo code —it cannot be executed on
a real computer, but it models and resembles real programming
code
© 2003 Prentice Hall, Inc. All rights reserved.
31
Pseudocode
Pseudo code is an informal language that helps programmers develop
algorithm without having to worry about the strict details of
programing language syntax. It has the following peculiar attributes:
➢ Steps are presented in a structured manner (numbered, indented, and
so on)
➢ No fixed syntax for most operations is required
➢ Less ambiguous and more readable than natural language
➢ Emphasis is on process, not notation
➢ Well-understood forms which allow logical reasoning about
algorithm behaviour
➢ It can be easily translated into a programming language.
© 2003 Prentice Hall, Inc. All rights reserved.
Pseudocode Format
Action Keywords: There are three basic actions that can be
carried out.
The SET, GET, and PUT keywords. They are used for these
actions.
• SET:
This is an action keyword that denotes performing some
operation that changes a value in memory.
• PUT:
This is an action keyword that denotes an output operation,
generally to the screen
• GET:
This is an action keyword that denotes in input operation,
© 2003 Prenticegenerally
Hall, Inc. All rights from
reserved. the keyboard.
33
Pseudocode Language Constructs
• The followings are the essential elements of Pseudocode language
construct
• Computation/Assignment
➢ Compute var1 as the sum of x and y
➢ Assign expression to var2
➢ Increment counter1
• Input/Output
➢ Input: Get var1, var2, …
➢ Output: Display var1, var2, …
© 2003 Prentice Hall, Inc. All rights reserved.
34
• Selection
❖Single-Selection IF
IF condition THEN (IF condition is true, then do subordinate
statement 1, etc. If condition is false, then skip statements)
✓ statement 1
✓ etc.
❖Double-Selection IF
– IF condition THEN (IF condition is true, then do subordinate statement 1, etc. If
condition is false, then skip statements and execute statements
under ELSE statement)
© 2003 Prentice Hall, Inc. All rights reserved.
35
✓ Statement 1,
✓ Statement 2, etc.
ELSE (else if condition is not true, then do subordinate statement 2,
etc.)
statement 2
statement 3
❖ SWITCH expression TO
case 1: action1
case 2: action2
etc.
default: action x
© 2003 Prentice Hall, Inc. All rights reserved.
36
• Repetition
WHILE condition (while condition is true, then do subordinate
statements)
statement 1
etc.
• DO – WHILE structure (like WHILE, but tests condition at the end of the
loop. Thus, statements in the structure will always be executed at least once.)
• DO
• statement 1
• etc.
© 2003 Prentice Hall, Inc. All rights reserved.
Pseudocode
• Example 1: Write an algorithm to determine a student’s final grade
and indicate whether it is passing or failing. The final grade is
calculated as the average of four marks.
© 2003 Prentice Hall, Inc. All rights reserved.
Pseudocode & Algorithm
Pseudocode:
• Input a set of 4 marks
• Calculate their average by summing and dividing by 4
• if average is below 50
Print “FAIL”
else
Print “PASS”
© 2003 Prentice Hall, Inc. All rights reserved.
Pseudocode
• Detailed Algorithm
• Step 1: Input M1,M2,M3,M4
Step 2: GRADE (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
© 2003 Prentice Hall, Inc. All rights reserved.
40
Pseudocode
• Example 2
• Express an algorithm to get two numbers from the user (dividend
and divisor), testing to make sure that the divisor number is not zero,
and displaying their quotient using pseudocode
© 2003 Prentice Hall, Inc. All rights reserved.
41
• Declare variables: dividend, divisor, quotient
• Prompt user to enter dividend and divisor
• Get dividend and divisor
• IF divisor is equal to zero, THEN
DO
Display error message, “divisor must be non-zero”
Prompt user to enter divisor
Get divisor
WHILE divisor is equal to zero
• ENDIF
• Display dividend and divisor
• Calculate quotient as dividend/divisor
• ©Display quotient
2003 Prentice Hall, Inc. All rights reserved.
Example: Pseudocode for computing miles per litre
STEP OPERATIONS
1 GET VALUES OF LITRES USED, STARTING MILEAGE,
ENDING MILEAGE
2 SET VALUE OF DISTANCE DRIVEN (ENDING MILEAGE-
STARTING MILEAGE
3 SET VALUE OF AVERAGE MILES PER LITRE TO(DISTANCE
DRIVEN – LITRES USED)
4 PRINT THE VALUE OF AVERAGE MILES PER LITRE
5 STOP
© 2003 Prentice Hall, Inc. All rights reserved.
43
FLOWCHART
• Flowchart is a graphical tool that diagrammatically depicts the steps
and structures of an algorithm or program.
▪ A flowchart is a diagram made up of boxes, diamonds and other
shapes, connected by arrows.
▪ Each shape represents a step in the process, and the arrows show
the order in which they occur.
▪ Flowchart combines symbols and flow-lines, to show figuratively
the operation of an algorithm.
© 2003 Prentice Hall, Inc. All rights reserved.
44
FLOWCHART SHAPES
SYMBOL NAME FUNCTION
Flow Lines Shows direction of flow.
Process Indicates any type of internal
operation inside the Processor or
Memory
Input / Output Used for any Input / Output
(I/O) operation. Indicates that the
computer is to obtain data
or output results
Decision Used to ask a question that can be
answered in a binary format
(Yes/No, True/False)
Off-page Connector Used to indicate that the flowchart
continues to the second page
© 2003 Prentice Hall, Inc. All rights reserved.
45
FLOWCHART SHAPES
SYMBOL NAME FUNCTION
Connector Allows the flowchart to be
drawn without intersecting lines or
without a reverse
flow.
Pre-defined Process Used to invoke a subroutine or an
Interrupt program.
Terminal Indicates the starting or ending of the
program, process, or interrupt program
Display Denotes an output operation
© 2003 Prentice Hall, Inc. All rights reserved.
General Rules for flowcharting
1. All boxes of the flowchart are connected with
Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top
of the symbol with no other entry points. The exit
point for all flowchart symbols is on the bottom
except for the Decision symbol.
3. The Decision symbol has two exit points; these
can be on the sides or the bottom and one side.
4. Generally a flowchart will flow from top to
bottom.
© 2003 Prentice Hall, Inc. All rights reserved.
Advantages of Using Flowcharts:
• Communication: Flowcharts are better way of
communicating the logic of a system to all concerned.
• Effective analysis: With the help of flowchart, problem
can be analysed in more effective way.
• Proper documentation: Program flowcharts serve as a
good program documentation, which is needed for various
purposes.
• Efficient Coding: The flowcharts act as a guide or
blueprint during the systems analysis and program
development phase. Proper Debugging: The flowchart
helps in debugging process.
• Efficient Program Maintenance: The maintenance of
© 2003 Prentice Hall, Inc. All rights reserved.
48
Example 1
• Flowchart for an algorithm which gets two numbers and prints sum
of their value
© 2003 Prentice Hall, Inc. All rights reserved.
Example 2
• Write an algorithm and draw a flowchart to convert the length in feet
to centimeter.
Pseudocode:
• Input the length in feet (Lft)
• Calculate the length in cm (Lcm) by multiplying LFT with 30
• Print length in cm (LCM)
© 2003 Prentice Hall, Inc. All rights reserved.
Example 2
Algorithm
Flowchart
• Step 1: Input Lft
• Step 2: Lcm Lft x 30 START
• Step 3: Print Lcm Input
Lft
Lcm Lft x 30
Print
Lcm
STOP
© 2003 Prentice Hall, Inc. All rights reserved.
Example 3
Write an algorithm and draw a flowchart that will read the two
sides of a rectangle and calculate its area.
Pseudocode
• Input the width (W) and Length (L) of a rectangle
• Calculate the area (A) by multiplying L with W
• Print A
© 2003 Prentice Hall, Inc. All rights reserved.
Example 3
Algorithm START
• Step 1: Input W,L
Input
• Step 2: A L x W W, L
• Step 3: Print A
ALxW
Print
A
STOP
© 2003 Prentice Hall, Inc. All rights reserved.
Example 4
• Write an algorithm to find the larger number between A
and B
Algorithm:
1. Read A, B
2. If A is less than B
3. BIG=B, SMALL = A
4. Else
5. BIG=A, SMALL = B
6. Write BIG, SMALL
• The flowchart is represented as:
© 2003 Prentice Hall, Inc. All rights reserved.
Example 4 contd.
© 2003 Prentice Hall, Inc. All rights reserved.
ANOTHER VERSION OF EXAMPLE 4
• Write an algorithm that reads two values, determines the largest value and prints
the largest value with an identifying message.
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX VALUE1
else
MAX VALUE2
endif
Step 3: Print “The largest value is”, MAX
© 2003 Prentice Hall, Inc. All rights reserved.
Example 4 Contd..
START
Input
VALUE1,VALUE2
Y is
N
VALUE1>VALUE2
MAX VALUE1 MAX VALUE2
Print
“The largest value is”, MAX
STOP
© 2003 Prentice Hall, Inc. All rights reserved.
PROBLEM
• Considering this algorithm,
1. Start
2. Sum = 0
3. Get a value
4. If the value is equal to –1,
5. Output Sum
6. Else
7. Sum = Sum + value
8. Go to step 3 to get next value
9. Stop
• Draw the flowchart
© 2003 Prentice Hall, Inc. All rights reserved.
for this algorithm
PROBLEM contd.
© 2003 Prentice Hall, Inc. All rights reserved.
Further Example 59
START
READ
NAME, SSN,
CREDITS
Pseudocode for Tuition problem
Start
NO CREDITS YES
≥ 10 ?
Read NAME, SSN, CREDITS
IF CREDITS >= 10 THEN
TUITION = TUITION = 1000 TUITION = 1000
100 * CREDITS
ELSE
TUITION = 100 * CREDITS
ENDIF
WRITE
NAME, SSN, TUITION Write NAME, SSN, TUITION
Stop
STOP
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm
• A control structure is a block of programming that
analyses variables and chooses a direction in which to
go based on given parameters.
• What kind of control structures are necessary to
describe algorithm?
• Types of Control Structure
➢ Sequence
➢ Selection
➢ Iteration (Repetition)
1. a way that, no condition step is required.
© 2003 Prentice Hall, Inc. All rights reserved.
61
• Sequence: The first type of control structures is called the sequence
structure. This structure is the most elementary structure. The
sequence structure is a case where the steps in an algorithm are
constructed one after the other
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm: Sequence
• For example, suppose you are required to design an
algorithm for finding the average of six numbers. and the
sum of the numbers is given.
• The algorithm will be as follows:
1. Start
2. Set Sum = 0
3. Input X1, X2 … X6
4. sum = X1 + X2 …+ X6
5. Set Average = Sum / 6
6. Output Average
7. Stop
© 2003 Prentice Hall, Inc. All rights reserved.
Selection Structure
• Selection Structure: The selection structure also known
as decision structure is a case in the algorithm where one
has to make a choice of two alternatives by making a
decision depending on a given condition.
• A selection structure takes the form:
If condition is true
Then do task A
else
Do Task-B
© 2003 Prentice Hall, Inc. All rights reserved.
64
Selection Structure
• This structure can be illustrated in a flowchart as follows:
© 2003 Prentice Hall, Inc. All rights reserved.
The Selection Structure e.g.
Pseudocode ➔
IF amount < 100 yes no
amount < 100
Interest Rate = .06
ELSE
Interest Rate = .10
ENDIF
interestRate = .06 interestRate = .10
© 2003 Prentice Hall, Inc. All rights reserved.
Selection Structure
• The selection requires the following:
➢ Choose alternative actions as a result of testing a logical condition
➢ Produce code to test a sequence of logical tests
• In making choices, IF statement is used together with
logical operators to test for true or false.
• The logical operators used are:
➢ = is equal to <= is less than or equal
➢ > is greater than <> is not equal to
➢ < is less than
➢ >= is greater than or equal
© 2003 Prentice Hall, Inc. All rights reserved.
Iteration or Repetition structures
3. Iteration or Repetition structures: The iteration
structure can be implemented using
• Repeat Until Loop • The While Loop • The For Loop
• Any program instruction that repeats some statement or
sequence of statements a number of times is called an
iteration or a loop. The commands used to create
iterations or loops are all based on logical tests.
© 2003 Prentice Hall, Inc. All rights reserved.
Iteration or Repetition structures
• Repeat Until Loop
The syntax is
REPEAT
A statement or block of statements
UNTIL
a true condition
• For example, A program repeatedly asking for an entry of a number
in the range 1 to 100 until a valid number is entered.
REPEAT
Output “Enter a number between 1 and 100”
UNTIL
number < 1 OR number > 100
© 2003 Prentice Hall, Inc. All rights reserved.
Iteration or Repetition structures
The While Loop
The second type of iteration. This type of conditional loop
tests for terminating condition at the beginning of the
loop. In this case no action is performed at all if the first
test causes the terminating condition to evaluate as false.
• The syntax is:
WHILE (a condition is true)
A statement or block of statements
ENDWHILE
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm
© 2003 Prentice Hall, Inc. All rights reserved.
Iteration or Repetition structures
• The For Loop: The third type of iteration. This, in its simplest
form, uses an initialisation of the variable as a starting point, a stop
condition depending on the value of the variable. The variable is
incremented on each iteration until it reaches the required value.
The syntax is:
FOR (starting state, stopping condition, increment)
Statements
ENDFOR
• For example:
FOR (n = 1, n <= 4, n + 1)
Output “loop”, n
ENDFOR
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm
• The fragment of code will produce the output
Loop 1
Loop 2
Loop 3
Loop 4
• In the example, n is usually referred as the loop
variable, or counter, or index of the loop.
• Example : Write an algorithm to calculate the sum and
average of a series of numbers.
© 2003 Prentice Hall, Inc. All rights reserved.
73
QUIZ
Instruction: Answer any two questions. Time allowed: 20
minutes
1. Design an algorithm and the corresponding flowchart for adding the odd
integers between 1 and 99
2. Write an algorithm to determine a student’s final grade and indicate whether
passed or failed. The final grade is calculated as the average of four marks.
3. If a = 1, b = 3, and x = 7,
What is the value of x when the loop terminates?
for(k = a; k < = b; k + 1)
{
x = x - k;
} // show your steps
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm
• Example: Design an algorithm and the corresponding
flowchart for finding the sum of n numbers.
• Algorithm
1. Start
2. Sum = 0
3. Input n
4. For(I = 1, I <= n, I+1)
5. Input a number
6. Sum = Sum + number
7. ENDFOR
8. Output Sum
9. Stop
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm
• In this example, we compare I with n to check whether we
have exhausted the numbers or not in order to stop the
computation of the sum (or to stop the iteration structure).
In such a case, I is referred to as a counter.
• The corresponding flowchart will be as follows:
© 2003 Prentice Hall, Inc. All rights reserved.
Control Structures of Algorithm
© 2003 Prentice Hall, Inc. All rights reserved.
EXERCISES
EX 1: Write an algorithm to determine a student’s final grade and indicate
whether passed or failed. The final grade is calculated as the average of four
marks.
Pseudocode:
1. Start
[Link] a set of 4 marks
3. Set their average by summing and dividing by 4
4. If average is below 50
5. Put “FAIL”
6. else
7. Put “PASS”
8. Stop
© 2003 Prentice Hall, Inc. All rights reserved.
EXERCISES
• The algorithm and flowchart is as follows:
START
1. Start
Input
2. Input M1,M2,M3,M4 M1,M2,M3,M4
3. GRADE = (M1+M2+M3+M4)/4 GRADE=(M1+M2+M3+M4)/4
4. If (GRADE < 50) then
5. Print “FAIL” No IS Yes
GRADE<50
6. else
7. Print “PASS” PRINT
“PASS”
PRINT
“FAIL”
8. Endif
9. Stop STOP
© 2003 Prentice Hall, Inc. All rights reserved.
EXERCISES
Ex 2: Write an algorithm that reads two values, determines the larger value and
prints the larger value with an identifying message.
ALGORITHM
1. Start
2. Input VALUE1, VALUE2
3. If (VALUE1 > VALUE2) then
4. MAX = VALUE1
5. else
6. MAX = VALUE2
7. Endif
8. Output “The largest value is”, MAX
9. Stop
© 2003 Prentice Hall, Inc. All rights reserved.
EXERCISES
START
Input
VALUE1,VALUE2
Y is
N
VALUE1>VALUE2
MAX =VALUE1 MAX =VALUE2
Output
“The largest value is”,
MAX
STOP
© 2003 Prentice Hall, Inc. All rights reserved.
NESTED IFS
• EX 3: given three numbers say N1, N2 & N3 write an
algorithm to find the largest number
1. Start
2. Input N1, N2, N3
3. If (N1>N2) then
4. if (N1>N3) then
5. MAX N1 // [N1>N2, N1>N3]
6. else
7. MAX N3 // [N3>N1>N2]
8. endif
9. else
10. if (N2>N3) then
11. MAX N2 // [N2>N1, N2>N3]
12. else
13. MAX N3 // [N3>N2>N1]
14. endif
15. endif
© 2003 Prentice Hall, Inc. All rights reserved.
NESTED IFS
16. Output “The largest number is”, MAX
17. Stop
© 2003 Prentice Hall, Inc. All rights reserved.
NESTED IFS
T F
F
T
© 2003 Prentice Hall, Inc. All rights reserved.