You are on page 1of 40

Introduction to Computers

Lecture 6 – Problem Solving II

“IF I had an hour to solve a


problem, I'd spend 55 minutes
thinking about the problem and five
m i n u t e s t h i n k i n g a b o u t s o l u t i o n s .”

~ Albert Einstein
Adding Test Scores

How to
improve ?

-2-
3. Repetition Structures

Loops (Repetitions) allows computers to perform


particular tasks repeatedly.

-3-
Repetition Structures

 The Repetition structure can be implemented using


 WHILE Loop
 DO WHILE (REPEAT-UNTIL) Loop

 FOR Loop

 Any program instruction that repeats a statement or


sequence of statements a number of times is called an
iteration.

 The commands used to create iterations or loops are


all based on logical tests.

-4-
Repetition Structures

 The statements that execute within a loop are

known as the loop body.

 A counter is any numeric variable you use to

count the number of times an event has occurred.

 Every time you add 1 to a variable is called

incrementing the variable.

-5-
Repetition Structures

There are two type of looping logics:


1. Counter Controlled Loop
 We know how many times loop body will be executed
 For example: print natural numbers from 1 to 100

2. Sentinel Controlled Loop


o Indefinite repetition because it is not known in advance
how many times the loop will be executed.
o Using a sentinel value (also called a signal value, a dummy
value or a flag value) to indicate the end of loop
o For example: Adds up any number of integers till the user
enters zero.
-6-
1. WHILE Loop

 This type of conditional loop


tests for terminating condition
at the beginning of the loop.
 No action is performed at all if
the first test causes the
terminating condition to
evaluate as false.
 Usually Sentinel-controlled.

WHILE condition
statements/body
ENDWHILE
-7-
How WHILE Loop Works?

 An algorithm that sums numbers from 1 to 1000


BEGIN
x=1 Test Condition
sum = 0
WHILE x <= 1000
sum = sum + x
Loop Body
x=x+1
ENDWHILE
PRINT sum
Incrementing the counter
END

-8-
How WHILE Loop Works?

 An algorithm that sums positive integers entered by


the user
BEGIN
sum=0
READ x
WHILE x > 0
sum = sum + x
READ x
ENDWHILE
PRINT sum
END
-9-
How WHILE Loop Works?

 The while loop evaluates the condition expression.


 If the condition expression is true, statements
inside the body of while loop are executed.
 Then, the condition expression is evaluated again.
This process goes on until the condition
expression is false.
 When the condition expression is false, while loop
is terminated.

-10-
WHILE Loop

 Make sure that the condition is actually going to turn


false at some point in time.
 If the condition is always true, then you will end up
in an infinite loop.
BEGIN Infinite
x=2
y=4 Loop
WHILE x<y
PRINT x, y
INCREMENT y
ENDWHILE
END
-11-
Class Average Algorithm

 Problem: Calculate and report the average


grade for a class of 100 students
 Discussion: The average grade equals the sum
of all grades divided by the number of students
Input: Student grades
Processing: Find the sum of the grades;
calculate average
Output: Average grade

-12-
Flowchart
Start

studentCount = 0
Sum = 0

No
studentCount < 100

Yes avg = Sum / 100


Read grade
Print avg

Sum = Sum + grade


Stop
Increment studentCount

-13-
Flowchart

If we do not know the


number of students in
advance

Stop

-14-
WHILE Loop: Example 2

 An algorithm that reads the exam results for 10


students and displays the numbers of passed and
failed students.
 A student passes if his mark is greater than or
equal to 60.

-15-
Start
WHILE Loop: Example 2
Set passes = 0
failures = 0
studentCount = 0
1

studentCount < 10 No

Yes Print passes,


Read grade failures

No Stop
grade >= 60
Yes
Increment passes Increment failures

1 Increment studentCount
WHILE Loop: Example 2 cont.

BEGIN
INIT passes = 0
INIT failures = 0
INIT studentCount = 0
WHILE studentCount < 10
READ grade Nested
IF grade>=60 THEN Construct
INCREMENT passes
ELSE
INCREMENT failures
ENDIF
INCREMENT studentCount
ENDWHILE
PRINT “Number of passed students: ”, passes, “ while “, failures, “
failed.”
END
-17-
WHILE Loop: Example 2 cont.

 An algorithm that reads the exam results for a


number of students and displays the numbers
of passed and failed students.
 A student passes if his mark is greater than or
equal to 60.

-18-
Start
Set passes = 0 WHILE Loop: Example 2
failures = 0
studentCount = 0
Read students

studentCount < students No

Yes Print passes,


Read grade failures

No Stop
grade >= 60
Yes
Increment passes Increment failures

1 Increment studentCount
WHILE Loop: Example 4

Get two numbers from the user and display their quotient.
Make sure that the divisor number is not zero.
Start

Read dividend, divisor


1
divisor = 0 No
Yes quotient = dividend/
Print “Divisor divisor
must be non-zero”

Print “Enter dividend Print quotient


and divisor”

Read dividend, Stop


divisor
1 -20-
2. DO-WHILE Loop

• This type of conditional loop tests for terminating


condition at the end of the loop.
• Executes at least once before checking the
condition.

DO
statements/body
WHILE condition
ENDWHILE

-21-
How DO-WHILE Loop Works?

 The codes inside the body of loop is executed at least


once. Then, the condition expression is checked.
 If the condition expression is true, the body of loop is
executed. This process continues until the condition
expression becomes false.
 When the test expression is false, DO-WHILE loop is
terminated.
 Just like with a WHILE loop, it is possible to end up
in an infinite loop, so it is very important to make
sure the end condition will always be met eventually.

-22-
DO-WHILE Loop: Example 1
What is
Start WRONG?

 An algorithm to read 100 count = 0


positive numbers then max =0

display the maximum. Read x


BEGIN
count=0
No
max = 0 x > max
DO
READ x Yes
IF x > max THEN max = x
max = x
ENDIF Yes
count < 100
WHILE count < 100
ENDWHILE No
Print max
PRINT max
END
Stop -23-
DO WHILE Loop: Example 2
Start
An algorithm that warmCities = 0
accepts readings of
city temperatures Read temperature

and displays the


No
number of warm temperature > 24
cities (>24). Yes
The program Increment warmCities
stops when user
Yes
enters a negative temperature >= 0
number. No
Print
warmCities

Stop -24-
DO WHILE Loop: Example 2 cont.

BEGIN
SET warmCities to zero
DO
READ Temperature
IF Temperature > 24 THEN
INCREMENT warmCities
ENDIF
WHILE Temperature >= 0
ENDWHILE
Print “Number of warm cities: “, warmCities
END

-25-
3. FOR Loop

 Counter-controlled: Used when the number


of iterations is known in advance.
FOR (initialization, condition, increment)
statements/body
ENDFOR
 Uses an initialization of the variable as a
starting point.
 The condition depends on the value of the
variable.
 The variable is incremented on each iteration
until it reaches the required value.
-26-
FOR Loop

-27-
FOR Loop

 The starting state section allows you to either


declare a variable and give it a value or give a
value to an already existing variable.
 The condition section tells the program that as
long as the conditional expression is true the loop
should continue to repeat itself.
 The increment/update section is the easiest way
for a for loop to handle changing of the variable.
It is possible to do things like x+1, x = x - 10, etc.

-28-
How FOR Loop Works?

1. The starting statement is executed only once at


the beginning.
2. Then, the condition expression is evaluated.
3. If the condition expression is false, FOR loop is
terminated. But if it is true, statements inside
body of FOR loop are executed and the increment
expression is executed.
4. Again, the condition expression is evaluated
and this process repeats until the condition
expression is false.

-29-
FOR Loop: Example 1

 An algorithm to calculate the sum of a set of


numbers.
BEGIN
sum=0
DISPLAY “How many numbers?”
INPUT count
FOR (i=1, i<=count, i+1)
INPUT num
sum=sum+num
ENDFOR
DISPLAY sum
END

-30-
FOR Loop: Example 1 cont.
Start

sum =0

Read count

i=1

1 No
i <= count
Yes Print sum
Read num
Stop
sum =sum + num

Increment i
1
-31-
FOR Loop: Example 2
Start
 An algorithm to
calculate the sum =0

average of a set of
i=1
numbers.
Read count
1 No
i <= count
Yes average=sum / count
Read num
Print average
sum =sum + num
Stop
Increment i
1 -32-
FOR Loop: Example 3

 An algorithm to Start
calculate the salary for Read numEmp
a number of hourly- i=1
paid employees.
1
No
i <= numEmp
Yes Stop
Read hours, rate

sal= hours * rate

Print sal

Increment i
1
-33-
FOR Loop: Example 3 cont.

BEGIN
DISPLAY “How many employees?”
INPUT numEmp
FOR (i=1 ,i<=numEmp, i+1)
INPUT hours, rate
sal = hours*rate
DISPLAY sal
ENDFOR
END

-34-
Which Loop to Use?

 There is usually more than one way to solve almost


every programming problem
 In case the program performs a specific number of
iterations → Use FOR
 In case the program performs an indefinite
number of iterations, as long as a certain condition
remains true → Use WHILE
 In case the program performs an indefinite
number of iterations and does not need a
condition at the start → Use DO..WHILE
-35-
Which Loop to Use?

 A company calculates the weekly wages of its


workers. The user submits the number of normal
and overtime hours of the workers. Payment for
normal working hour is 14 while for overtime
working hour is 18…
 If the number of workers is 10 FOR

 If the user enters many workers and wants to choose


when to stop WHILE

 If we know that the company has at least one worker


and the user wants to choose when to stop DO
WHILE
-36-
Exercise: Complete
1. The statements that execute within a loop are known as
the -----.
2. In the ----- design structure, statements can be executed
or skipped depending on whether a condition evaluates
to True or False.
3. The ----- in the FOR loop handles changing the value of
the variable.
4. The ----- loop is used when processes should be executed
at least once.
5. If the condition is always true, then you will end up in an
----- loop.

-37-
Exercise: True/False

1. All boxes of the flowchart are connected with lines.


2. The WHILE loop is used in case the program performs an
indefinite number of iterations, as long as a certain
condition remains true.
3. Nested IF is used in case of multiple embedded decisions.
4. An algorithm can be defined as a difference between a
desired situation and current situation.
5. The FOR loop is used in case the program performs an
indefinite number of iterations and does not need a
condition at the start.
6. Every Nested IF can be represented using Case selection.

-38-
Practice – Design An algorithm for:

1. A program that outputs the square of any number


input until the number input is zero.
2. A program that finds the smallest of user-defined
number of integers.
3. A program that calculates and prints the product
of the odd integers from 1 to 15.

-39-

You might also like