0% found this document useful (0 votes)
14 views27 pages

Problem Solving With Loops

Uploaded by

farhan.segujja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views27 pages

Problem Solving With Loops

Uploaded by

farhan.segujja
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

1

CSC 1106
Introduction to Programming and
Problem Solving | Fundamentals of
Computer Programming

Problem Solving with Loops

BsCS|BIT
Lecture Outline

At the end of this lecture, you should be able to:


 Develop Solutions using the loop logic structure in conjunction with the
 decision and sequential logic structures.

 Use problem-solving tools when developing a solution using the loop logic
structure.
 Use counters and accumulators in a problem solution.
 Use nested loop instructions to develop a problem solution.
 Distinguish the different uses of three types of loop logic structures.

© IUIU – 2021. 10/30/2024

Walusimbi Hakim |
The Loop Logic Structure
3

 A third logic structure for designing decisions is the loop structure, the
loop logic structure is the repeating structure.
 Most problems in business involve doing the same task over and over for

different sets of data, so this structure is extremely important.


 Through the loop structure, a program can process many payroll records

or inventory items or put a mailing list in alphabetical or zip code order.


 The main concern in using it as part of a solution is identifying what

instructions should be repeated.

© IUIU – 2021. 10/30/2024


The Loop Logic Structure
4

 Besides being used to repeat instructions in a solution, the loop structure is


also used to return the processing to an earlier point in the solution.
 When it is used in this way, it is a replacement for the GoTo statement.

 The GoTo is an instruction that tells the computer to transfer to another instruction in
the solution instead of processing the next instruction in sequence.
 Replacing the GoTo statement in this way increases the readability of the
program.

© IUIU – 2021. 10/30/2024


Types of loop structures
5

 There are three types of loop structures


 While/WhileEnd Loop, which repeats a set of instructions while a condition
is True and stops repeating when the condition is False.
 Repeat/Until Loop, which repeats a set of instructions while a condition is

False or until a condition is True


 Automatic-counter loop, in which a variable is set equal to a given

number and increases in equal given increments until it is greater than an


ending number.
 The algorithm and the flowchart differ with each type of loop structure.

© IUIU – 2021. 10/30/2024



6

 It is extremely important to indent the instructions in algorithms using the


loop structure as it is with the decision structure
 to improve readability.
 Also, nested loops are common, and in these solutions indentation with
bracketing allows you to easily identify each loop.
 Several standard types of tasks are accomplished through the use of the

loop structure.
 These include;

 Counting (also called incrementing and decrementing).


 Accumulating (also called calculating a sum or a total).

© IUIU – 2021. 10/30/2024



7

 In both tasks, a number is added or subtracted from a variable and the


result is stored back into the same variable.
 The basic difference between counting and accumulating is in the value

that is added or subtracted.


 When counting, the value is a constant; when accumulating, the value is a variable.
 In each case, the resultant variable is assigned the value of zero before
starting the loop.
 This is called initializing the variable.

© IUIU – 2021. 10/30/2024


Incrementing
8

 The task of incrementing, or counting, is done by adding a constant, such


as 1 or 2, to the value of a variable.
 To write the instruction to increment a variable, you use an assignment

statement.
 For example,

 Counter = Counter + 1 or C = C + 1
 When counting by ones, an assignment statement allows the variable on
the left side of the equal sign to be assigned the value of, or to be
replaced by, the resultant of the expression on the right side of the equal
sign.

© IUIU – 2021. 10/30/2024


Incrementing
9

 The counter or incrementor instruction is a special version of the


assignment instruction.
 This instruction enables the programmer to count the number of items,

people, temperatures, and so on as part of the solution to a problem.


 Notice the structure of the assignment instruction for incrementing, the

same variable name is on both sides of the equal sign; the amount the
variable is to be incremented follows the plus sign.
 This instruction takes the value of the counter, adds one to it, and then

replaces the old value of the counter with the new.

© IUIU – 2021. 10/30/2024


Incrementing
10

 The increment can be by 1, 2, or any other constant, including negative


numbers if you want to decrement rather than increment.
 In this example, Counter or C must be initialized to zero before starting

the loop.

© IUIU – 2021. 10/30/2024


Accumulating
11

 Another task that a program must often perform is accumulating or


summing a group of numbers.
 The process of accumulating is similar to incrementing, except a variable

instead of a constant is added to another variable, which holds the value


of the sum or total.
 The instruction for accumulating is the following:

 For example, the instruction to find total sales would be

© IUIU – 2021. 10/30/2024


Accumulating
12

 Like the instruction to increment, the instruction to accumulate is a special


version of the assignment instruction.
 The same variable name appears on both sides of the equal sign

(TotalSales), but in accumulating, a variable rather than a constant is on


the right-hand side of the plus sign (Sales in this case).
 In other words, with an accumulator, you are adding a variable (the item

you are accumulating) to the value of another variable, which holds the
sum or total.
 In these examples, Sum and TotalSales must be initialized to zero before

starting the loop.

© IUIU – 2021. 10/30/2024


Accumulating
13

 Calculating the product of a series of numbers is similar to finding the sum


of a series of numbers, with two exceptions.
 First,
the plus sign is replaced by the multiplication sign (*).
 Second, the product variable must be initialized to 1 instead of 0.

 For example:

© IUIU – 2021. 10/30/2024


While/WhileEnd
14

 This type of loop tells the computer that while the condition is True, repeat
all instructions between the While and the WhileEnd.
 The form of the algorithm is the following:

 The symbol used for the While part of the instruction is the diamond, the
symbol for a decision.

© IUIU – 2021. 10/30/2024


While/WhileEnd
15

 Since this flowchart shows only part of an algorithm, on-page connectors


are used. The completed algorithm would have one part that would
connect to A and another part that would connect to B.

© IUIU – 2021. 10/30/2024


While/WhileEnd
16

 At the beginning of the While/WhileEnd loop, the program processes the


condition in order to decide whether to execute the loop instructions, as
illustrated in the diamond at the top of the flowchart.
 When the resultant of the condition is False at the start, the instructions

within the loop will not be executed.


 When the resultant of the condition is True, the complete set of instructions

will be executed, and then the computer will go back to the beginning of
the loop and process the condition again.
 The loop will repeat until the resultant of the condition is False, at which

time the processing will continue with the instruction following the
WhileEnd.
© IUIU – 2021. 10/30/2024
While/WhileEnd
17

 We use the While/WhileEnd structure when you do not know the number
of times the instructions will be repeated, or if there are cases when the
instructions in the loop should not be processed.
 In those cases, the resultant of the condition is False at the start of the

loop, so the loop is not processed.


 Examples of such cases are

 When you are entering information on clients and you don’t know the number of
clients;
 When you are finding the total amount of sales for the day and you don’t know the
number of sales; or
 When you are calculating test averages for each student in a class.

© IUIU – 2021. 10/30/2024


While/WhileEnd
18

 In the case of calculating test averages, the loop instructions should not be
executed for students who for some reason have no test grades.
 To calculate the average you would accumulate and count the test scores

and then divide the total score by the number of tests.


 Since the number of grades would be zero for the student who didn’t take

any tests, the computer would try to divide by zero, and an error would
result.
 The While/WhileEnd loop would enable the processing to pass over the

student and go on to the next student.

© IUIU – 2021. 10/30/2024


Problem - While/WhileEnd Solution
19

 Create the algorithm and the flowchart to find the average age of all the
students in a class.
 The first instruction initializes the value of the Sum (the total of all ages) to

zero.
 The second instruction initializes the value of the counter variable to zero.

 Next the first age is entered, an age must be entered before the loop so

that the condition has data to use to get a resultant.


 This is called a primer Read because it gives the While/WhileEnd loop a

valid value for the variable Age in order for the conditions to be true the
first time through the loop.
 If there is no primer Read, the value of Age is unknown.
© IUIU – 2021. 10/30/2024
20

© IUIU – 2021. 10/30/2024


Problem - While/WhileEnd Solution
21

 The next read is at the end of the loop for two reasons. First, the first
value of Age must be included in the calculations.
 Second, the test for the trip value (the value of age that makes the

condition false and signals the end of the list of students) must be just
before the condition, so the trip value will not be calculated as part of
the average age.
 The While begins the loop and processes the condition Age When the

resultant is True, the instructions in the loop are processed; when the
resultant is False, the processing continues with the calculation of the
average.

© IUIU – 2021. 10/30/2024


Problem - While/WhileEnd Solution
22

 The first loop instruction accumulates the ages by adding each age to the
total, followed by an instruction that counts the students by adding one to
the counter variable.
 The final instruction in the loop enters the next age, the processing then

returns to process another condition.


 The last age should be zero, this zero is called a trip value, or a flag, It

allows the value of Age to control when to stop the looping process and
continue with the rest of the solution.
 When the looping process stops, the processing continues at the

calculation of the average age, and finally, the printing of the average
age.
© IUIU – 2021. 10/30/2024
Problem - While/WhileEnd Solution
23

 The data for this problem can be entered from the keyboard; the user
enters a 0 when there are no more ages to enter.

© IUIU – 2021. 10/30/2024


24

© IUIU – 2021. 10/30/2024


Loop Control Statements
25

 Loop control statements are used to change the flow of execution.


 These can be used if you wish to skip an iteration or stop the execution.

 Loops are used to iterate repeatedly over a block of code, to change the

way a loop is executed from its usual behavior, we use control statements.
 Control statements are used to control the flow of the execution of the

loop based on a condition.


 The two types of loop control statements are

 break

 and continue.

© IUIU – 2021. 10/30/2024


Break Statement
26

 Based on the given condition, the break statement stops the execution and
brings the control out of the loop.
 There can be many cases when a break statement can be used.

 For example, if we want to stop the execution when an item is of a

certain datatype (int, dict str, etc.) or if it equals a certain value, we can
use the break statement.

© IUIU – 2021. 10/30/2024


Continue Statement
27

 The Continue statement is used to skip the current iteration when the
condition is met and allows the loop to continue with the next iteration.
 It does not bring the control out of the loop unlike the break statement.

© IUIU – 2021. 10/30/2024

You might also like