You are on page 1of 71

CSC 128:

FUNDAMENTALS OF
COMPUTER PROBLEM
SOLVING

TOPIC 4: REPETITION CONTROL


STRUCTURE

LOGO
Contents

1 Introduction

2 while loop

3 for loop
Introduction
 It is used when a statement or a block of
statements need to be executed several
times.
 Programmers use the repetition structures,
referred to more simply as a loop, when they
need the computer to repeatedly process
one or more program instructions until some
condition is met, at which time the repetition
structures end.
 Repetition is also known as iteration or loop.
Introduction – example
 Let say, you want to display “ I love
C++” 5 times.

void main()
{
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;
cout << “ I love c++!\n”;

}
Repetition control structures
 C++ provides a few types of loop
structures:
 while loop
 for loop
The while loop

LOGO
while loop
 Repeat or loop as long as the condition
is true.
 The general form of the while
statement is:
while (loop condition)
{
//loop body
statement;
}

 while is a reserved word.


 The parentheses are part of the syntax
while loop
while (loop condition)
{
//loop body
statement;
}

 Loop condition acts as a decision maker


and is usually a logical expression.
 A Boolean expression that controls the execution of the
body of the loop
 statement executes if the condition initially evaluates to true
 loop condition is then reevaluated
 statement continues to execute until the condition is no
longer true
while loop
 The general form of while loop
flowchart:

Loop false
condition

true

Statement (s)
(loop body)
while loop
 The following while loop prints I love
C++ 5 times.
Loop control variable

int count = 1;

while(count<= 5)
{
cout<< “ I love C++”;
count ++;
}
while loop

Start

count = 1

count <= T
5

I love C+
F +

count++

End
Loop control variable
 A LCV controls the number of times
the statement or the block of
statements is being executed.
How many times this loop will execute??

int count = 0;

while(count < 10)


{
cout<< “ hello ”;
count ++;
}
while loop
 Basic operation in loop:
 Initialization
 Evaluation
 Update
while loop
 The following while loop prints I love
C++ 5 times.

int count = 1; //initialization

while(count<= 5) //evaluation
{
cout<< “ I love C++”;
count ++; //update statement
}
while loop

 Update statement:

 count ++;
OR
counter
 count = count + 1;
 Requirement of a repetition structure
Flow Chart
Loop body

Initialize counter = 1
LCV

counter T
<= 5

I love C+
F +
Evaluate
LCV (loop condition) counter ++

Update
LCV
while loop
 Example: to display the first five
positive integers which increment by
five.
while loop
 Pseudocode:

Begin
Initialize i to 0
Repeat while i <= 20
Display i
add 5 to i (update)
End repeat while
End
while loop
Start

i = 0
Enter the Expression evaluates
while statement to zero
i <= 20 End
False condition
Expression
True condition evaluates to a
nonzero number

Loop
Display
i

i = i + 5

Go back and reevaluate


the expression
while loop
 Example C++ program segment:
1) Loop Control 2) A starting point / Initialization of the LCV
Variable (LCV)

i = 0;
while ( i <= 20)
{
cout << i << “ “;
i = i + 5;
}
3) Testing the loop repetition
condition
4) Updating the LCV
while loop
 Various form of while loops:
 Counter controlled
 Sentinel controlled
while loop – counter control
 If you know exactly how many pieces
of data need to be read, the while
loop becomes a counter-controlled
loop.
 General syntax:
while loop – counter control
 Counter controlled while loop includes the
following:
◦ Counter
 A numeric variable used for counting something

counter = counter + 1
 Is done by adding a constant, such as 1 or 2, to the value of
a variable.

◦ Accumulator
 Numeric variable used to find totals

sum = sum + variable


 Is done by adding a variable to another variable
while loop – counter control
 Counter controlled while loop includes the
following:
◦ Initializing
 Assign a beginning value to the counter or accumulator;
typically 0
◦ Updating
 Also called incrementing, means adding a number to the
values stored in the counter or accumulator.
while loop – counter control

#include <iostream>
#include <conio>

int main() initializing


{
int count;

count = 1;

while (count <= 10)


{
cout << count << endl;
count++;
}

getch();
return 0; updating
}
while loop – counter control
 Example: to find and display total of
three numbers
 Pseudocode:
Begin
Initialize lcv to 0, total to 0
Repeat while lcv is less than 3
input number
total = total + number
Update lcv
End repeat while
display total
End
while loop – counter control
 Program and output
void main()
{
int lcv,total;
lcv = 0, total =0;
while (lcv < 3)
{
cout << “enter number" << endl;
cin>> number;
total = total + number;
lcv++;
}
cout<<“the total is”<<total;
getch();
}
while loop – counter control

Exercise: Write a C++ statement


associated to the following flowchart.
Begin

Initialize
counter = 10

T
Display counter Add 10 to
counter < 100 Multiplied by 2 counter
F

End
while loop – counter control
 Program and output
int main()
{
int count;

count = 10;

while (count < 100)


{
cout << count * 2 << endl;
count += 10;
}

getch();
return 0;
}
while loop – sentinel control
 A sentinel-controlled while loop uses
a special value called sentinel to
control the loop.
 Sentinel value is a special value that indicates the end
of a set of data or of a process
 Sentinel variable is tested in the
condition and loop ends when sentinel
is encountered
while loop – sentinel control
 General syntax :
while loop – sentinel control
 Example
#include <iostream>
#include <conio>
int main()
{
char answer;
cout << "Do you want to quit (Y - yes, N - no) : ";
cin >> answer;
Sentinel value
while (answer != 'Y')
{
cout << "Welcome to the program." << endl;
cout << "Do you want to quit (Y - Yes, N - No) : ";
cin >> answer;
}
cout << "Bye.";
getch();
return 0;
}
while loop – sentinel control
 Output screen
while loop – sentinel control
 Exercise 1: to create a program to
calculate and print total of a few
numbers and the program will stop
and display the result when a value
333 is read.
while loop – sentinel control
void main()
{
int number, total;
total= 0;
cout << "Enter a number : ";
cin >> number;
while (number != 333)
{
total = total + number;
cout << "Enter a number : ";
cin >> number;
}
cout <<"You have entered 333 to terminate”
<<“the program.“<<endl;
cout <<“the total is “<<total;
getch();
}
while loop – sentinel control
 Exercise 2: to create a flowchart and
C++ program that process the loop as
long as user enter an even number
while loop – sentinel control
 Solution
 Flowchart

Begin

Prompt for
a number

Get
a number

T Get another
number % 2 == 0
number

F
End
while loop – sentinel control
 Program

int main()
{
int number;
cout << "Enter a number : ";
cin >> number;
while (number % 2 == 0)
{
cout << "Enter the next number : ";
cin >> number;
}
cout <<"You have entered an odd number to terminate”
<<“the program.";
getch();
return 0;
}
while loop – sentinel control
 Output
while loop
 Infinite loop
 continues to execute endlessly
 can be avoided by including statements in the loop
body that assure exit condition will eventually be
false

{
while (answer != 'Y')
{
cout << "Welcome to the program." << endl;
cout << "Do you want to quit (Y - Yes, N - No) : ";
cin >> answer;
}
cout << "Bye.";
}
The for loop

LOGO
for loop
 Also called as a counted or indexed for
loop
 The general form of the for statement is:

for ([initial statement]; loop condition; [update statement])


statement;
 The initial statement, loop condition, and
update statement are called for loop
control statements
 Items in square brackets ([ ]) are
optional.
for loop
for ([initial statement]; loop condition; [update statement])
statement;

 The for loop executes as follows:

1. The initial statement executes.


2. The loop condition is evaluated. If the loop condition
evaluates to true
i. Execute the for loop statement.
ii. Execute the update statement (the third expression
in the parentheses).
3. Repeat Step 2 until the loop condition evaluates to false.

 The initial statement usually initializes a variable.


 In C++, for is a reserved word.
for loop – Example 1
 Example : Displaying star symbol
three times.
initialization condition update

for (int count = 1; count <= 3; count = count + 1)


cout << “*” << endl;

Result:
*
*
*
for loop – Example 1
 Using for loop to display ‘Welcome to
C++’ three times.
 Pseudocode:

Start
for( set i to 1; i less than or equal to 3;
add 1 to i)
display “welcome to C++”
End for
End
for loop – Example 1
 Flowchart Start

i=1

F
i <= 3 End

T
Display
“welcome to C+
+”

i ++
for loop – Example 1
 C++ program

initialization condition update

for (int count = 1; count <= 3; count = count + 1)


cout << “welcome to C++” << endl;
for loop – Exercise 1
 To create a program to display the
first 10 non negative number.
for loop – Exercise 2
 To create a program to display
backward the first 10 non negative
number.
for loop – Exercise 3
 Exercise 3: create a program that
display the first 10 positive odd
integers.
for loop – Exercise 3
 Exercise 3 - answer
for loop – Exercises
 How many time the following loop
processed?

for (int count = 6; count < 6; count = count + 1)


cout << count << endl;

 Answer:
for loop – Exercises
 How many time the following loop
processed?

for (int count = 4; count <= 10; count = count + 2)


cout << count << endl;

 Answer:
for loop – Example 3
 Example: to calculate and display
total of 3 numbers
for loop – Example 3
 Pseudocode:

Start
Initialize total = 0
For(set counter to 1; counter less than or
equal to 3; add 1 to counter)
input number
total = total + number
Endfor
Display total
End
for loop – Example 3
 Flowchart Start

counter=1, total = 0,

for F
counter Output
<= 3 total
T
Input End
number

total = total + number


counter = counter + 1
for loop – Example 3
 C++ program segment

total = 0;

for (int count = 1; count <= 3; count = count + 1)


{
cin>>number;
total = total + number;
}
cout << “total:” <<total<<endl;
for loop – Exercises
 Suppose j, sum, and num are int variables, and the input
values are 26, 34, 61, 4, and -1. What is the output of the
code below?

cout << "Enter a number : ";


cin >> num;

for (j = 1; j <= 4; j++)


{
sum = sum + num;
cout << "Enter a number : ";
cin >> num;
}
cout << sum << endl;
for loop – Exercises
 Exercise 4: answer
for loop
 A semicolon at the end of the for
statement (just before the body of
the loop) is a semantic error. In this
case, the action of the for loop is
empty.
 In the for statement, if the loop
condition is omitted, it is assumed to
be true.
 In a for statement, you can omit all
three statements—initial statement,
loop condition, and update statement.
The following is a legal for loop:
for loop
for (;;)
cout << "Hello" << endl;

 This is an infinite loop, continuously


printing the word Hello
Nested Control Structures

LOGO
Nested loop
 In many situations, it is very
convenient to have a loop contained
within another loop.
 Such loops are called nested loops.
 For each single trip, through the outer
loop, the inner loop runs through its
entire sequence.
 Each time counter i increases by 1, the inner loop
executes completely.
Nested loop
 Example of C++ program segment

for (i = 0; i <= 1; i++)


{
cout << "\n i is now " << i << endl;

for (j = 1; j <= 4; j++)


cout << " j = " << j ;
}
Nested loop
 How it works…
Outer loop i is now 0
j = 1 j = 2 j = 3 j = 4 Inner loop

i is now 1
j = 1 j = 2 j = 3 j = 4
Nested loop
 Suppose we want to create the
following pattern.
*
**
***
****
*****
 In the first line, we want to print one
star, in the second line two stars and
so on.
Nested loop
 Since five lines are to be printed, we
start with the following for statement.
for (i = 1; i <= 5 ; i++)
 The value of i in the first iteration is
1, in the second iteration it is 2, and
so on
 Can use the value of i as limit
condition in another for loop nested
within this loop to control the number
of starts in a line.
Nested loop
 The syntax

for (i = 1; i <= 5 ; i++)


{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
Nested loop
 What pattern does the code produce if
we replace the first for statement
with the following?

for (i = 5; i >= 1; i--)


 Answer:

*****
****
***
**
*
Summary
 Two types of loop:
 Pretest loop
• Evaluation occurs before the instructions within the loop
are processed
• Instruction may never be processed
• while statement, for statement

 Posttest loop
• Evaluation occurs after the instructions within the loop
are processed
• Instructions will be processed at least once
• do..while statement
www.themegallery.com

LOGO

You might also like