0% found this document useful (0 votes)
15 views24 pages

Chapter 4

cs

Uploaded by

nikzamzuri225
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)
15 views24 pages

Chapter 4

cs

Uploaded by

nikzamzuri225
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/ 24

CHAPTER 4

REPETITION/ITERATION
CONTROL STRUCTURE
Prepared by: Siti Hasrinafasya Che Hassan
Reference to: D.S. Malik
Overview

• Introduction to Repetition Structure


• Types of Repetition Structure
• Repetition Structure
➢ For loop
➢ While loop
➢ Do..while loop
• Nested loop

2
Introduction to Repetition Structure
Repetition control structure allows a sequence of statement to
be executed repeatedly until certain condition is reached.
• Requirement of a repetition structure:
1. Loop Control Variable (LCV):
→ a variable that determines
whether the loop body will be for(<condition>)
executed.
{
2. Loop condition:
<body>
→ if the condition is true, the
loop body is executed, }
otherwise the loop exits.
3. Loop body:
→ statement to be repeated.
3
Introduction to Repetition Structure
• Execution of the loop body is controlled by 3 operations:
1. Initialization of LCV
2. Evaluation of the loop condition
3. Update LCV by incrementing or decrementing

• Example: Print “I love C++” for 5 times. Output:


int max = 5;
Initialize LCV Condition Update LCV

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


{
cout << “I love C++” << endl;
}
4
2 Types of Repetition Structures
1. Counter controlled repetition structure:
• Used when the number of repetition is fixed.
• Example:

Enter marks for 10 students.


float mark;
int students = 10; 3
1 2
for(int count = 1; count <= students; count++)
{
cout << “Enter marks of student “ << count << “: “;
cin >> mark;
cout << “Marks for student “ << count << “ is “ << mark << endl;
}

Remember the THREE (3) requirements of repetition structure!


5
2 Types of Repetition Structures
2. Sentinel controlled repetition structure:
SENTINEL value is a value used to terminate the loop process.
• Used when the number of repetition is depending
on the certain condition.
• THREE (3) steps involved:
1. Get the Sentinel value.
2. Evaluation of the loop condition.
3. Get back the Sentinel value.
<Get a sentinel value>
while(<condition>)
{
<block of statement(s)>
<Get a sentinel value>
}
6
2 Types of Repetition Structures
• Example: Repeat a process until user input a value to
terminate the process.
Print a “Yes, I love C++!” statement for more than one line until an user asks
to stop.
char response;
cout << “Do you want to proceed or stop? (Y or N): “;
1 cin >> response; A sentinel value
2 while(response
1. Get== the‘Y’ || responsevalue.
sentinel == ‘y’)
{
2. <<Evaluation
cout of the
“Yes, I love C++!” loop condition.
<< endl;
3. <<Get
cout “Do back
you wantthetosentinel
continue oncevalue.
more again? (Y or N): “;
3 cin >> response;
}

Remember the THREE (3) steps of sentinel repetition structure!


7
3 Forms of Repetition Structures

• Repetition structure in C++ comes in THREE (3) forms:


1. for loop
2. while loop
3. do…while loop

8
For Loop

• It is a counter controlled loop.


• Syntax:
1 2 3
for (initialization; condition; update) 1. Execute the initialization statement.
2. While the condition remains true,
{ 2 execute the block of statement(s).
<statementBlock>; 3. Then, update expression.
}
where:
➢ initialiazation = initialization of LCV
➢ condition = evaluation of loop condition
➢ update = updating of LCV
➢ statementBlock = either single statement or a group of
statement enclosed between braces

9
For Loop (Examples)
• Example 1:
Sum up the sequence of numbers starting from 1 until 10
int sum = 0; 1. Execute the initialization
1 2 3
for (int number = 1; number <= 10; number++) statement.
{ 2. While the condition remains true,
2 execute the block of statement(s).
sum += number; // sum = sum + number; 3. Then, update expression.
}
cout << “The sum is “ << sum << endl;

• Example 2:
Find the summation of 5 numbers entered by an user
int num, sum = 0;
for (int i = 1; i <= 5; i++)
{
cout << “Enter a number “ << i << “: “;
cin >> num;
sum += num;
}
cout << “The sum is “ << sum << endl; 10
For Loop (Examples)

• Example 3:
Find the maximum number among 6 positive numbers entered by
user
Int num, max = 0;
for(int count = 0; count <= 5; count++)
{
cout << “Enter a number “ << (count + 1) << “: “;
cin >> num;
if ( num > max)
max = num;
}
cout << “The maximum number is “ << max << endl;

11
While Loop

• Employs a pretest loop.


• Syntax:
1
<initialization>; 1. Execute the initialization statement.
2 2. While the condition remains true,
while (condition) execute the block of statement(s).
{ 3. Then, update expression.
<statementBlock>; 2
<update>; 3
}
where:
➢ initialiazation = initialization of LCV
➢ condition = evaluation of loop condition
➢ update = updating of LCV
➢ statementBlock = either single statement or a group of
statement enclosed between braces
12
While Loop (Example – Counter)

Counter controlled loop


• Example 1:
Find the summation of 5 numbers entered by an user.
int num, sum = 0;
int count = 0; Initialization of LCV
while (count <= 4) Evaluate loop condition
{
cout << “Enter a number : “ << (count + 1) << “: “;
cin >> num;
sum+= num;
count++; Update loop LCV
}
cout << “The sum is “ << sum << endl

13
While Loop (Example - Sentinel)
Sentinel controlled loop
• Example 2:
Calculate the square root of any numbers as long as the number
entered is greater or equal than 10. Then, count how many numbers
that have been calculated by a program.
int x, s, count = 0;
cout << " Enter any number: ";
cin >>x; Get the sentinel value
while (x >= 10) Evaluate loop condition
{
count = count + 1;
s = sqrt(x);
cout << " Square root of " << x << " is " << s << endl;
cout << " Enter any number: ";
cin >> x; Get back the sentinel value
cout << endl;
}
cout << “The numbers that have been calculated is “ << count; 14
While Loop (Examples)

• Example 3:
Find the maximum number among 6 numbers entered by user
int x, max = 0;
int count = 0;
while (count <= 5)
{
cout << “Enter a number “ << (count + 1 ) << “: “ ;
cin >> x;
if ( x > max)
max = x;
count++;
}
cout << “The maximum number is “ << max << endl;

15
While Loop (Examples)
• Example 4:
Find an average salary entered by the user
double salary, avg;
double sum=0; if (count > 0) {
int count=0; avg = sum /count;
bool more = true; Use bool data type cout << "The average salary is " << avg << endl;
}

Flag controlled loop


cout << " The program is starting..." << endl; else
while(more == true) cout << “The program is terminating…”;
{
cout << " Enter salary amount : ";
cin >> salary;
if (salary == 0)
more = false;
else
{
count++;
sum=sum + salary;
}
}

16
Checkpoint 1

1 Search the highest and lowest of salaries among the employees


entered by an user, based on the:
i) Counter controlled loop (use a for loop)
ii) Sentinel and flag controlled loop (use a while loop)

The sample of both programs as follows:

Program i) Program ii)

17
Checkpoint 2
2 i) Find an average of quizzes for a student.
ii) Extends program 2i) above, repeat until an user enters
negative marks (including zero).
iii) Modify program 2ii) above, where an user is given an
option to stop the program.
iv) Change program 2iii) above, in which the program will
continually procced until -1 is entered.
Use the following outputs:

Program i) Program ii)

Program iv)
Program iii) 18
Do…While Loop

Initialization
Syntax:
Initialization
Action(s)
<initialization>;
do
{
Updating
Action(s) <statementBlock>;
<update>;
} while (condition);
Updating

Pretest for for and while loops Posttest for do…while loop

19
Do…While Loop (Examples)
1 int i = 0; int i = 0;
do while (i <= 20)
{ {
cout << i << “ “; cout << i << “ “;
i = i + 5; i = i + 5;
} }
while (i <= 20);

2 int i = 11; int i = 11;


do while (i <= 10)
{ {
cout << i << “ “; cout << i << “ “;
i = i + 5; i = i + 5;
} while (i <= 10); }

20
Nested Loop

• A loop (inner loop) as one of the statements in the body of another


loop (outer loop).
• Syntax:
for (intialization1; condition 1; updating1) intialization1;
{ while (condition 1)
for(intialization2; condition 2; updating2) {

Outer loop
{ intialization2;
Inner loop statementBlock2; while (condition 2)
} {
statementBlock1; statementBlock2;
} updating2;
}
statementBlock1;
updating1;
}
Nested for loop Nested while loop
21
Nested Loop (Examples)
• Example 1:
There are 30 students in a class. Find an average of 5 quizzes for
each student.
const int noOfStudents = 30; if(sumQuiz > 0)
const int noOfQuiz = 5; {
float quizMarks; avgQuiz = sumQuiz/noOfQuiz;
}
for(int countStud = 1; countStud <= noOfStudents; countStud++) cout << " The average of quiz marks for student "
{ << countStud << " is " << avgQuiz
float sumQuiz = 0.0, avgQuiz = 0.0; << endl << endl;
}
cout << " Student " << countStud << endl;
cout << " " << setw(20) << setfill('-') << endl;
for(int countQuiz = 1; countQuiz <= noOfQuiz; countQuiz++)
{
cout << " Enter marks of quiz " << countQuiz << ": ";
cin >> quizMarks;

sumQuiz = sumQuiz + quizMarks;


}

22
Nested Loop (Examples)
• Example 2:
Extends from the program in Example 1, find the highest marks
of quiz obtained for each 30 students.
const int noOfStudents = 30; cout << " The highest of quiz marks for student "
const int noOfQuiz = 5; << countStud << " is " << highestQuiz
float quizMarks; << endl << endl;

for(int countStud = 1; countStud <= noOfStudents; countStud++) }


{
float highestQuiz = 0.0;

cout << " Student " << countStud << endl;


cout << " " << setw(20) << setfill('-') << endl;
for(int countQuiz = 1; countQuiz <= noOfQuiz; countQuiz++)
{
cout << " Enter marks of quiz " << countQuiz << ": ";
cin >> quizMarks;

if(quizMarks >= highestQuiz)


highestQuiz = quizMarks; Checkpoint 2:
} Search the highest of quiz marks from the overall students.
23
ANY QUESTION…?

24

You might also like