0% found this document useful (0 votes)
13 views35 pages

07 - Branching and Loop (Part 2)

This document discusses the fundamentals of loops in programming, including their structure, types (pre-test and post-test), and components such as body, condition, initialization, and updating. It provides examples of loop statements in C++ like while, for, and do..while, along with exercises for practice. Additionally, it covers nested loops and how to translate flowcharts into C++ code.

Uploaded by

Enoch
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)
13 views35 pages

07 - Branching and Loop (Part 2)

This document discusses the fundamentals of loops in programming, including their structure, types (pre-test and post-test), and components such as body, condition, initialization, and updating. It provides examples of loop statements in C++ like while, for, and do..while, along with exercises for practice. Additionally, it covers nested loops and how to translate flowcharts into C++ code.

Uploaded by

Enoch
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/ 35

TOPIC 07

BRANCHING AND LOOP (PART 2)


Fundamentals of Computing
(FSPK0022)
Loop/ Repetition
Loop/ Repetition
• The main idea of a loop is to repeat an action or a
series of actions.
• But, when to stop looping?
• In the following flowchart, the
action is executed over and over
again. Its never stop.
– This is called an infinite loops.
• Solution: put a condition to tell
the loop either to continue
looping or stop.
Loop

• A loop has two parts: body


and condition.
• Body: a statement or a block
True Body
of statements that will be
repeated.
• Condition: is used to control
the iteration, either to Condition
continue or stop iterating.
False
Types of Loop

Pre-test loop
• Two forms of loop:
– Pre-test loop
– Post-test loop
Condition
• Pre-test loop Here must be a

– The condition is tested first, True


“True”

before we start executing the


body. Body False

– The body is executed, if the


condition is true.
– After executing the body, the
loop repeats.
Types of Loop

Post-test loop
• Post-test loop
– The condition is tested later,
after executing the body. True Body
– If the condition is true, the
loop repeats, otherwise it
terminates.
– The body is always executed at Condition
least once.
The iterating part
must be a “True”
False
Parts of a Loop
• Beside the body and condition, a loop may have two other
parts: initialization and updating.
Pre-test loop Post-test loop

Initialization Initialization

Body
Condition
True

True
Updating

Body

False
Condition
Updating

False
Parts of a Loop
• Initialization Post-test loop
– Is used to prepare a loop before
it can start  usually, here we Initialization

initialize the condition.


– The initialization must be written Body

outside of the loop, before the True

first execution of the body. Updating

• Updating
– Is used to update the condition. Condition

– If the condition is not updated, it False


always true  the loop always
repeats (an infinite loop)
– The updating part is written inside the loop. It is actually a part
of the body.
Example 1: Parts of a Loop
• These flowcharts print numbers 10 down to 1.

Pre-test loop Post-test loop

Initialize n before start the


n=10 n=10
loop

Print
is n>0? n
True

True
n = n -1
Print
n

False

n = n -1
Every time the loop is n>0?
repeats, n is updated

False
Loop Statements

• C++ provides three loop statements:


while Statement

while flowchart
while(condition)
{
Repeated_actions; Condition
}
True

Repeated_Actions False
while Statement

Example: Print numbers 10 down to


1 using while statement. n=10

Note: The first line (n = 10) is


actually not a part of the loop statement.
is n>0?
n = 10;
while (n > 0) True
{ Print
cout << n << “ ”; n

False
n = n-1;
} n = n -1

Output:

10 9 8 7 6 5 4 3 2 1
for Statement

for flowchart
for(Initialization;
Condition; Updating) Initialization

{
Repeated_actions; Condition

} True

Repeated_Actions

False

Updating
for Statement

Example: Print numbers 10 down to


1 using for statement.
n=10

for(n = 10; n > 0; n = n - 1)


{
cout << n << “ ”; is n>0?
}
True

Print
n
Output: False

n = n -1
10 9 8 7 6 5 4 3 2 1
for vs. while Statements

Comparing for and while loops


do..while Statement

do..while flowchart
do
{
Repeated_actions;
True Repeated_Actions
} while(condition);

Condition

False
do..while Statement

Example: Print numbers 10 down to


1 using do..while statement. n=10

Note: The first line (n = 10) is


actually not a part of the loop statement.
n = 10; Print
n
do True

{
n = n -1
cout << n << “ ”;
n = n-1;
} while (n > 0);
is n>0?

Output:
False

10 9 8 7 6 5 4 3 2 1
Loop Statements
• If the body part has only one statement, then the
bracket symbols, { } may be omitted.
• Example:
These two for statements are equivalent.

for(n = 10; n > 0; n = n - 1)


{
cout << n;
}

for(n = 10; n > 0; n = n - 1)


cout << n;
Breaking Out of a Loop
• Can use break to terminate execution of a loop.
• When used in an inner loop, terminates that loop
only (inner loop) and returns to the outer loop.
Exercise 1
• Determine the output of each code segment below:
 int x = 10;
do {
x++;
if (x % 2 == 1 ) continue;
cout << x << ", ";
} while (x <= 21);
 int y = 2;
do {
if (y > 500 ) break;
cout << y << ", ";
y *= 3;
} while (y > 1);
Exercise 2
• Rewrite the following program segment using a do..while
loop:
int count = 0, x;
int n = 5;
int i = 0;
while (i < n)
{
cin >> x;
if (x == i)
++count;
++i;
}
cout << "count = " << count;
Exercise 3
• Rewrite the following code fragment so that it uses a
while loop to accomplish the same task:
int n;
do
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n < 0)
cout << "The integer you entered is "
<< "negative." << endl;
} while (n < 0);
Translating Flowchart to C++ Code
• Pattern 1

Here must be a while(condition)


“False”
{
condition
Repeated_actions;
Here must be a

True
“True”
}

Repeated_Actions False
Translating Flowchart to C++ Code
• Example of pattern 1: Calculate the average of odd numbers 1 to 9.

sum = 0
i =1 sum = 0;
i = 1;
i < 11 while (i < 11)
True
{
sum = sum + i sum = sum + i;
i = i+2
False
i = i + 2;
}
avrg = sum / 5.0;
av rg = sum /5
Translating Flowchart to C++ Code
• Pattern 2

do
True Repeated_Actions
{
Repeated_actions;
} while(condition);

condition

The iterating part


must be a “True”

False
Translating Flowchart to C++ Code
• Example of pattern 2: Prints numbers 1 to 10.

i =1 i = 1;
do
PRINT
{
True
i
cout << i << endl;
i = i +1
i = i + 1;
} while (i < 11);
i <11

False
Translating Flowchart to C++ Code
• Pattern 3 for(initialize;
condition; update)
initialize
{
Repeated_Actions;
}
condition

True
initialize;
while(condition)
Repeated_Actions

False
{
update Repeated_Actions;
update;
}
Translating Flowchart to C++ Code
• Example of pattern 3: Print the total of numbers 1 to 10.

total = 0
total = 0;
for (i = 1; i < 11; i++)
i=1
{
total = total + i;
}
cout << total;
i<11

True total = 0;
total = total + i
i = 1;
False
while (i < 11)
i=i+1 {
total = total + i;
i++;
PRINT }
total
cout << total;
Start

Exercise 4 count = 0
positive= 0
• The following flowchart negative = 0

presents an algorithm of a
False
program that counts the count < 30
Display
End
positive,
number of positive and negative
True
negative numbers entered by
the user. The user will enter Input
number
30 numbers. Translate the
flowchart into its
corresponding C++ program True
number > 0 positive = positive + 1
using an appropriate loop
statement. False

True
negative = negative + 1
number < 0

False

count = count + 1
Exercise 4 (cont.)
• Write your code in the incomplete program given below:
#include <iostream>
using namespace std;

int main()
{
int count = 0; //The total count of numbers entered
int positive = 0; //The count of positive numbers
int negative = 0; //The count of negative numbers
int number; //The number entered

//Write your code here


//...
//...
//...
return 0;
}
Deciding Which Loop to Use

• while: pretest loop (loop body may not be


executed at all).
• do..while: post test loop (loop body will always
be executed at least once).
• for: pretest loop (loop body may not be executed
at all); has initialization and update code; is useful
with counters or if precise number of repetitions is
known
Nested Loops
• A nested loop is a loop inside the body of another
loop.
• Example: outer loop

for (row = 1; row <= 3; row++) inner loop


{
for (col = 1; col <= 3; col++)
{
cout << row * col << endl;
}
}
Notes on Nested Loops
• Inner loop goes through all its repetitions for each
repetition of outer loop.
• Inner loop repetitions complete sooner than outer
loop.
• Total number of repetitions for inner loop is
product of number of repetitions of the two loops.
In previous example, inner loop repeats 9 times.
Exercise 5
• How many times the outer loop is executed? How many
times the inner loop is executed? What is the output?
#include <iostream>
using namespace std;
int main()
{
int x, y;
for(x = 1; x <= 8; x += 2)
for(y = x; y <= 10; y += 3)
cout << "\nx = " << x
<< " y = “ << y;
return 0;
}
Exercise 6
• Determine the output of each code segment below:
for (int i = 1; i < 4; i++)
{
int j = i;
while (j > 0)
{
cout << "i = " << i
<< ", j = " << j << endl;
j--;
}
}

You might also like