0% found this document useful (0 votes)
5 views64 pages

CSC 126 CH4

Chapter 4 covers repetition control structures in programming, explaining the necessity of loops for executing statements multiple times until a condition is met. It details various types of loops, including 'for' and 'while' loops, and provides pseudocode examples for calculating sums, averages, and finding maximum or minimum values. The chapter emphasizes the importance of loop control variables and the initialization, evaluation, and update processes within loops.

Uploaded by

2024223538
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)
5 views64 pages

CSC 126 CH4

Chapter 4 covers repetition control structures in programming, explaining the necessity of loops for executing statements multiple times until a condition is met. It details various types of loops, including 'for' and 'while' loops, and provides pseudocode examples for calculating sums, averages, and finding maximum or minimum values. The chapter emphasizes the importance of loop control variables and the initialization, evaluation, and update processes within loops.

Uploaded by

2024223538
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/ 64

CHAPTER 4: REPETITION CONTROL

STRUCTURE
CSC126|Fundamental of Algorithms & Computer Problem Solving
TABLE OF CONTENT

• Introduction
• Requirement of repetition structure
• while statement
• Basic iterative problems
• for statement
• Nested loops
INTRODUCTION
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.

Write I LOVE YOU 100 times


ITERATION CONTROL
STRUCTURE
Write an algorithm that will ask user to input 5 numbers,
What will happen if the algorithm
then calculate the average of it. Output the average value. need the user to repeat inserting
more then 5 numbers?
Start 10 numbers ?
initialize sum with 0 100 numbers?
display “Enter 5 number :“ 1000 numbers?
read no1,no2,no3,no4,no5
sum = no1+no2+no3+no4+no5
average = sum / 5

Solution ?
display “The total is“, average
End

Iteration/ repetition/ loop


control structure
REQUIREMENT OF REPETITION
STRUCTURE

• Execution of the loop body is controlled by 3 operation:


• Initialization
• Evaluation/ condition/ end value
• Update
REQUIREMENT OF REPETITION
STRUCTURE: INITIALIZATION

• Process of assigning value to a loop control variable.


• Example of statement:

counter = 0 number = 2

Loop Control Variable (LCV)


REQUIREMENT OF REPETITION STRUCTURE:
EVALUATION/ CONDITION/ END VALUE

• It controls the number of times the statement or the block of statements is


being executed.
• Examples:

counter <=10 status != ‘N’

number != 999
REQUIREMENT OF REPETITION
STRUCTURE: UPDATE

• Is done by adding/ subtracting a constant, such as 1 or 2, to the value of a


variable.
• Examples:

counter = counter + 1 counter ++

counter = counter - 1 counter --

number = number – 2
REQUIREMENT OF REPETITION
STRUCTURE

Pseudocode Initialize LCV

Begin
counter = 1
evaluate LCV
Depend on type of loop Repeat (counter <= 5)
structure use ( while, output “I love C++”
do … while or counter ++
for) update LCV
End

Variable counter is known as LCV


REQUIREMENT OF REPETITION
STRUCTURE

Flow Chart
Loop body
Start

Initialize Counter = 1
LCV

Counter T
<= 5

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

End Update
LCV
REPETITION STRUCTURES

• There are two types of repetition can be implemented.


• Counter Loop
• Is used when the number of repetition is identified
• Loop structures:
❖ while
❖ do … while
❖ for
• Sentinel Loop
• Is used when the number of repetition is unknown
• Loop structures:
• while
• do … while

The while and do … while loop can be used to implement both type of
repetition control structure.
COUNTER CONTROL LOOP
FOR LOOP
INTRODUCTION

• 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.
INTRODUCTION

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).
• Repeat Step 2 until the loop condition evaluates to false.
• The initial statement usually initializes a variable.
• In C++, for is a reserved word.
INTRODUCTION

• Example : Displaying numbers 1 through 3

initialization condition update

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


cout << count << endl;

Result:
1
2
3
FOR LOOP – EXAMPLE 1

• Using for loop to display ‘Welcome to C++’.


• Pseudocode:

Start
For( set i to 1; i less than or equal to 3; add 1 to i)
display “welcome to C++”
Endfor
End
FOR LOOP – EXAMPLE 1

Start
• Flowchart

i=1

F
i <= 3 End

Display “welcome to
C++”

i ++
for LOOP – EXAMPLE 2

• Example: to create a program to display backward the first 10 non negative


number.
for LOOP – EXERCISES

• Exercise 1: create a program that display the first 10 positive odd integers.
for LOOP – EXERCISES

• Exercise 1 - answer
for LOOP – EXERCISES

• Exercise 2: how many time the following loop processed?

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


cout << count << endl;

• Answer:
for LOOP – EXERCISES

• Exercise 3: how many time the following loop processed?


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

• 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


B ASIC ITERATIVE PROBLEMS

• List of iterative problems that can be solved using for loop structures:
✓ Calculate total/ sum
✓ Calculate average
✓ Find maximum or minimum value
✓ count
B ASIC ALGORITHM USING for LOOP
STRUCTURE

• Calculate sum or total:


Task:To calculate total of 5 numbers

total = 0;
*Accumulator used to calculate total
for(i = 1; i <= 5; i++){
cin>>number;
total = total + number;}
cout<<“ The total is :”<<total;
for LOOP – EXERCISES 1
( CALCU LAT E TOTAL)

❖ Exercise 4: 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? Produce tracing table.

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 1
(CALCULATE TOTAL)

❖ Exercise 4: answer
for LOOP – EXERCISES 2
( CALCU LAT E TOTAL)

MAR 2016
B ASIC ALGORITHM USING for LOOP
STRUCTURE

• Calculate average:
Task:To calculate average of 5 numbers
total = 0;
average = 0;

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


cin>>number;
total = total + number;}

average = total/ (i -1);


cout<<“ The average is :”<<average;
B ASIC ALGORITHM USING for LOOP
STRUCTURE

• To find maximum value:


Task:To find maximum value of 5 numbers
*count start at 2 because first number
had been entered before the loop

cin>>number;
max = number; max = -1;

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


{ {
cin>>number; cin>>number;
if(number>max) if(number>max)
max = number; max = number;
} }
cout<<“ The maximum value is :”<<max; cout<<“ The maximum value is :”<<max;
B ASIC ALGORITHM USING for LOOP
STRUCTURE

• To find minimum value:


Task:To find minimum value of 5 numbers
*count start at 2 because first number
had been entered before the loop

cin>>number;
min = number; min = 1000;

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


{ {
cin>>number; cin>>number;
if(number<min) if(number<min)
min = number; min = number;
} }
cout<<“ The minimum value is :”<<min; cout<<“ The minimum value is :”<<min;
for LOOP – EXERCISES 1 (MAX)

MAR 2017
B ASIC ALGORITHM USING REPETITION
STRUCTURE
• Count
Task: user requires to input 5 numbers. Calculate and
display how many even numbers in a group of 5 numbers entered.

countE = 0; *counter used to count amount of


even number
for(i = 1; i <= 5; i++)
{
cin>>number;
if(number%2==0)
countE= countE + 1;
}
cout<<“ The amount of even numbers are :”<<countE;
for LOOP – EXERCISES 1
(COUNT)

Write a complete C++ program to allow user to input 10


numbers using for loop. Count and display how many
numbers that can be divisible by 2 and by 5.
WHILE LOOP (COUNTER
CONTROL)
while LOOP COUNTER CONTROL

• The pseudocode for while…endWhile statement for loop:

Initial value of a loop (initialization)


while (condition)
statement(s) to be repeated
statement to update the condition (update statement)
endWhile
while LOOP COUNTER
CONTROL
• The flowchart for while…endWhile statement for loop:

Initialize the loop

condition
NO

YES

Statement(s) to repeat

Statement(s) to make the loop stop

EXIT FROM THE LOOP


while LOOP COUNTER CONTROL

• General syntax:

LCV = initial_value; //initialize the LCV


while(LCV <= final_value)//expression test the LCV
{
statement_to_be_executed;
:
LCV = LCV + step; //update the LCV
}
while LOOP COUNTER CONTROL

LCV = initial_value; • Loop condition acts as a decision maker and is


while(LCV <= final_value) usually a logical expression.
{
• A Boolean expression that controls the execution
statement_to_be_executed; of the body of the loop
:
LCV = LCV + step; • 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 COUNTER CONTROL
• Consider:
int count = 0; //initialize the LCV
while (count < 3) //test the LCV
{
cout << “Hi” << endl; //Loop Body
count = count + 1; //Update LCV

• Loopcount
body executes how many times?
count < 3 Output
(count = count + 1)
0 0 < 3 (T) Hi
1 1 < 3 (T) Hi So, loop body
executes 3 times
2 2 < 3 (T) Hi
3 3 < 3 (F) exit
EXERCISES

MAR 2017
B ASIC ITERATIVE PROBLEMS

• List of iterative problems that can be solved using while loop


counter control structures:
✓Summation
✓Average
✓Counting
✓Minimum
✓Maximum
• Examples as shown in the following slides.
SUMMATION

• Calculate sum or total:


Task:To calculate total of 5 numbers

total = 0;
i = 1;
while(i <= 5){ *Accumulator
cin>>number;
total = total + number;
i++;
}
cout<<“ The total is :”<<total;

• Accumulator – to find totals.


sum = sum + variable

• Is done by adding a variable to another variable.


SUMMATION

total = 0; Sample data: 10 5 4 6 8


i = 1; Produce tracing table for the above sample data
while(i <= 5){
total = 0 i=1 i<=5 cin>>number total=total+number i++ cout<<total
cin>>number;
total = total + number; 0 1 T 10 10=0+10 2
i++;
} T 5 15=10+5 3
cout<<“ The total is :”<<total; T 4 19=15+4 4

T 6 25=19+6 5

T 8 33=25+8 6

F - - - 33
SUMMATION - EXERCISE

APR 2009
AVERAGE

• Calculate average:
Task:To calculate average of 5 numbers

total = 0;
average = 0;
i = 0;
while(i < 5){
cin>>number;
total = total + number;
i++;
}

average = total/i;
cout<<“ The average is :”<<average;
AVERAGE

total = 0; Sample data: 10 25 4 6 30


average = 0;
Produce tracing table for the above sample data
i = 1;
total = 0 i=1 i<=5 cin>>number total=total+number i++ average=total cout<<total
while(i <= 5){ /i
cin>>number;
total = total + number;
i++;
}

average = total/(i-1);
cout<<“ The average is :”<<average;

Depends on how u initialize your LCV


AVERAGE – EXERCISE

APR 2009
MAXIMUM

• To find maximum value:


Task:To find maximum value of 5 numbers

*count start at 2 because first number Assume -1 is the maximum value


had been entered before the loop
Style 1 Style 2
cin>>number;
max = number; max = -1;
i=2 i=1
while( i <= 5) while( i <= 5)
{ {
cin>>number; cin>>number;
if(number>max) if(number>max)
max = number; max = number;
i++; i++;
} }
cout<<“ The maximum value is :”<<max; cout<<“ The maximum value is :”<<max;
MAXIMUM

cin>>number; Sample data: 10 50 4 6 30


max = number;
Produce tracing table for the above sample data
i=2
while( i <= 5)
{
cin>>number;
if(number>max)
max = number;
i++;
}
cout<<“ The maximum value is :”<<max;
MAXIMUM

Sample data: 25 4 6 30 10
max = -1;
Produce tracing table for the above sample data
i=1
while( i <= 5)
{
cin>>number;
if(number>max)
max = number;
i++;
}
cout<<“ The maximum value is :”<<max;
MINIMUM

• To find minimum value:


Task:To find minimum value of 5 numbers
Assume current minimum value 1000
*count start at 2 because first number
had been entered before the loop

cin>>number; min = 1000;


min = number; i = 1;
i = 2; while( i <= 5)
while( i <= 5) {
{ cin>>number;
cin>>number; if(number<min)
if(number<min) min = number;
min = number; i++;
i++; }
} cout<<“ The minimum value is :”<<min;
cout<<“ The minimum value is :”<<min;
MINIMUM - EXERCISE

OCT 2012
COUNTING

• Count
Task: user requires to input 5 numbers. Calculate and
display how many even numbers in a group of 5 numbers entered.
*counter used to count amount of even number

countE = 0;
i=1
while( i <= 5)
{
cin>>number;
if(number%2==0)
countE= countE + 1;
i++;
}
cout<<“ The amount of even numbers are :”<<countE;
COUNTING - EXERCISE

• Write a complete C++ program to allow user to input 10 numbers using while
loop. Count and display how many numbers that can be divisible by 3 and by 5.
DO … WHILE (COUNTER
CONTROL)
DO … WHILE CONTROL STRUCTURES

• The general form of a do. . .while statement is as follows:

• The statement executes first, and then the expression is evaluated. If the expression evaluates to true, the
statement executes again.
• As long as the expression in a do...while statement is true, the statement executes.
• To avoid an infinite loop, you must, once again, make sure that the loop body contains a statement that
ultimately makes the expression false and assures that it exits properly.
DO … WHILE CONTROL STRUCTURES

1. Start of do while loop.


2. The body of do while loop.
3. The test expression or condition to be evaluated.
4. If the test expression is true, the C++ compiler executed the body of do
while loop.
5. If the test expression is false, the C++ compiler executes the statements after
the loop body.
6. Statements that come after the loop body.
DO … WHILE CONTROL STRUCTURES

• Example:
DO … WHILE CONTROL STRUCTURES

• Sum of Positive Numbers Only:

Summation
TO BE CONTINUED…

You might also like