Topic 8 - Problem Solving Concepts - Part 4
Topic 8 - Problem Solving Concepts - Part 4
Mohamed Hussein
Faculty of Computers & Information Technology
Outline
Repetitive Structure (Loops)
Basic Algorithmic Structures
Design of an Algorithm
An algorithm is written as a step-by-step procedure
(sequence) in which choices can be made where
necessary (selection), and all or part of the
algorithm can be repeated (repetition).
Pseudocode
Flow Chart
Programming Languages
3
Repetition
Write an algorithm that will display
the numbers 1 - 10.
Using the knowledge you currently
possess, you would most likely write a
program that uses individual lines of
code that print out each number. Display 1
Display 2
The pseudo code for such Display 3
an answer looks like this.
Display 4
But, this not a practical
Display 5
efficient algorithm,
Display 6
especially, if the problem
is changed to display the Display 7
numbers 1 – 100. Display 8
The algorithm for such Display 9
problem is solved using: Display 10
iteration, also known as
Repetition or loops.
Repetition
count = count + 1;
n = n % m;
5-5
Repetition – while loop
The while loop has the following structure:
while (Condition)
{
Statement list
T Statement }
Condition
list
7
Repetition – while loop
The algorithm to display the numbers 1-10, using a while
loop, would be as follows:
Algorithm
step1: x = 1
Step2: while ( x <= 100 )
{
OUTPUT x
x = x + 1
}
step3: STOP
do
{
statement-list
} while (loop repetition condition)
Algorithm
step1: x = 1
Step2: do
{
OUTPUT x
x = x + 1
}while(x <= 10)
step3: STOP
Discussion
Without loops, solving this problem is impossible: In
essence, (without loops) you would need to have an
infinite number of read statements all in a row to perform
this task. Instead, we notice that as long as the user has
not entered –1, repeat the addition and read statements.
Remember, always look for indications that you will be
repeating something.
Repetition
The algorithm that prints the summation of a set of integers
entered by the user. The user will stop entering the integers by
input -1
Algorithm
step1: sum = 0
step2: INPUT x
step3: while ( x != -1)
{
sum = sum + x
INPUT x
}
step4: OUTPUT sum
step5: STOP
Before this decision can be made, you must input the first number
(outside the loop). If the condition is true, we can add this number to
the sum and read the next one. The second and subsequent times
user input is read, it is done inside the loop.
Step1: Sum = 0
Step2: INPUT a, b
Step3: while (a <= b)
{
Sum = Sum + a
a = a + 1
}
Step1: Sum = 0
Step2: INPUT a, b
Step3: while (a <= b)
{
if ( a % 2 == 0 )
Sum = Sum + a
a = a + 1
}
Exercise
step2: while(x<=1000)
{ sum=sum+x
x=x+1 }
step4: average=sum/1000
step6: stop
1-start
2-x=1 , input grade, sum=0
3-while(x<=100)
{sum=sum + grade
Input grade
x=x+1
}
4- average=sum/100
5-display average.
6-stop