0% found this document useful (0 votes)
22 views51 pages

Chap06 - Looping

The document discusses repetition or looping control structures in C++ programming, including how to construct for, while, and do-while loops using initialization, condition, and updating statements. It explains the differences between pre-test and post-test loops and provides examples of using loops in event-controlled and counter-controlled situations. The document also covers breaking and continuing loops using break and continue statements.

Uploaded by

chanky-wp22
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)
22 views51 pages

Chap06 - Looping

The document discusses repetition or looping control structures in C++ programming, including how to construct for, while, and do-while loops using initialization, condition, and updating statements. It explains the differences between pre-test and post-test loops and provides examples of using loops in event-controlled and counter-controlled situations. The document also covers breaking and continuing loops using break and continue statements.

Uploaded by

chanky-wp22
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/ 51

C++ Programming:

Problem Solving and


Programming
Chapter 6
Repetition
loop-repeat a statement continuesly until the condition false

Objectives
In this chapter you will:
• Learn about repetition (looping) control
structures
• Explore how to construct and use count-
controlled, sentinel-controlled, flag-controlled,
and EOF-controlled repetition structures
• Examine break and continue statements
• Discover how to form and use nested control
structures
2
Concept of Looping

• A loop is a group of
instructions the
computer executes
repeatedly while
some looping
continuation
condition remain
syntax of for loop
TRUE. ----------------------
for(initialization;condition;counter){
for(int text=1;text<=200;text++){
statement;
cout<<text<<".Hello!
}
Welcome to C++Language class
}
Hello!Welcome to C++ language Class
print the text above for 100 times
**continue at pg 29**
3
pattern in for loop
*
psedocode of while loop
**
-------------------------------- ***
1.initialize count to 0 *** *
2.prompt and get input print this triangle pattern using one cout<<"*"<<" ";
3.WHILE input GREATER THAN 1
prompt and get input learn about nested loop
increment count by 1
Endwhile
4.Display input and count

to construct 4 key words Two types of loop:


1.Initialization A. pre-test
2.condition
3.statement pre-test
4.updating/counter - the action will be execute when the
condition is true

1.while loop- event based controller(e.g.


user withdraw money and give us to
control user until insufficient)

syntax of while loop


--------------------------
example applying while loop
initialization;
int count,input; while(condition){
cout<<"Enter first number:"; statement;
cin>>input; updating
while (input>1){
cout<<"Enter next number:"; }
cin>>input;
//how many times the loop performed 2.for loop-counter based(give us to
//count=count+1; control user with 3 times to key in pin
0=0+1 number)
//count+=1 post-test- the action will be executed at
count++; least once if the condition is false
} one type
cout<<"Last value is"<<input<<",loop was performed"<< count<<endl; 1.do..while loop
4
Pre-Test Loop

• The condition is
checked at the false
beginning of each Condition
iteration (loop)
true

Actions

5
Pre-Test Loop
• In each iteration (loop),
the condition is tested
false first.
Condition
• If it is TRUE, the loop
true continues. Otherwise,
the loop terminates.
Actions
• This structure is possible
not executing any
actions at all.

6
Pre-Test Loop
• Example:
Set ball counter to 0
While box is not empty
Take a ball from box
Increase ball counter by 1
End While
Print ball counter

7
Post-test Loop

• The condition is checked


Actions at the end of each loop

true
Condition

false

8
Post-test Loop
• In each loop, the loop
actions are executed.
Actions Then the condition is
tested.
true • If it is TRUE, a new loop
Condition
starts. Otherwise, the
false loop terminates
• This structure performs
the actions at least once.

9
Post-test Loop
• Example:
Set ball counter to 0
Do
Take a ball from box
Increase ball counter by 1
While box is not empty
Print ball counter

10
Exercise
• Based on the general algorithms above, what
will happen to each type of loops if the box is
initially empty?

11
Loop Condition,
Initialization & Update
• Other than condition, commonly there are 2
more processes (initialization and updating)
associate with loops.

12
Loop Condition,
Initialization & Update
Initialization
Set student counter = 1
spell it(GREATER THAN OR
SMALLER THAN)
While student counter <= 3
Condition
Print “Congratulation”
Add 1 to student counter
End While
Action Print “You are late”

Updating

This loop will repeat for 3 times

13
Loop Condition,
Initialization & Update
Notes:
 It is important to write your initialization,
condition and updating statements correctly. If
not, the loop will either never repeat or never
stop (i.e. an endless loop).

14
15
Event-Controlled Loop

 The loop will be terminated when an event


changes the loop control expression
(condition) from TRUE to FALSE.

16
Event-Controlled Loop

Set total to 0
This loop keeps
Do repeating as long
Read number as the user
response is “Yes”.
Add number to total
Print “Anymore (Yes/No)?” Event: The user
Read response response.

While response = “Yes”


Print total

17
Counter-Controlled Loop

• Used when we know the number of times


action(s) are being repeated.
• In this case, we will use a variable as a
counter to repeat the action(s).

18
Counter-Controlled Loop
Initialize the
control variable
(student counter).
Set student counter = 1
While student counter <= 3 Condition tests
Print “Congratulation” the value of the
Add 1 to student counter control variable.
End While Update the
Print “You are late” control variable.

19
Looping Control Structures
syntax for do...while loop

• 3 types: ---------------------------------
initialization;
do{
statement;
update;

−while loops }while(condition);

−for loops Example of do...while loop

int number1, number2,sum=0;


do{
cout<<"Enter two numbers:";

−do-while loops
cin>>number1>>number2;
sum=number1+number2;
cout<<"Sum of"<<number1<<"and"<<number2
<< "is" << sum<<endl;
cout<<"Do you wish to cintinue>(y/n)";
cin>>answer;
}while(answer=='y');

20
while loops
• It is a pre-test and
event-controlled loop. false
Condition
• Action is run repeatedly
while the condition is true true
• Syntax: Actions

while (condition)
{ The braces { and } can be
action ignored if there is only 1
statement in the body of a
} while loop.
21
while loop - Example
• Write a program that finds the value of 2
multiply itself 10 times by using a while
statement.

22
while loop - Example
#include <iostream>
using namespace std;
int main() Initialization
{
int x = 2;
int count = 1;
Condition
while (count <= 10)
{ accumulator

x = x * 2;
count++; Updating
}

cout << "The result is “<< x;

return 0; } 23
while loop – Exercise
• Write a loop to print out the even numbers from
500 to 2.

Answer:
Algorithm
int i=500;
capi
tal
lett
set counter to 500
er while counter >= 2 while(i>=2)
print counter value {
subtract 2 from counter cout << i << endl;
end while
i-=2;
}
24
while loop – Exercise
Answer:
• Write a loop to
int x=2, count=1, sum=0;
print the sum
double average;
and average of
even numbers while(x<=10) {
from 2 to 10. sum = sum + x;
x+=2; // same as x=x+2;
count += 1;
}
average = sum / count;
cout <<“ sum: ”<<sum << endl;
cout << “average:”<<average;
25
Sentinel Value
• Sentinel value is a special value that causes
a loop to stop
• It cannot confuse with the valid value,
example: -999 for a test score
• Used when user may not know how many
values to be entered during input process

26
Sentinel Value - Example

cannot counted

total+=total+points

AACS2524 Programming Concepts 27


for loop
• It is a pre-test and expr1
(Initialization)
counter-controlled loop
•Syntax : False
expr2
(Condition)
Initialization Condition
True

Action
for ( expr1; expr2; expr3 )
expr3
{ (condition)
action updating
} Updating

28
continue

for loop
• A for loop contains 3 major components:
− expr1: Initialization of control variable.
− expr2: Loop continuation condition.
− expr3: Updating (increment / decrement) of
control variable. pattern
*
**
***
****
//first for loop to create row
for(int row=1;row<=4;row++){
//second for loop for print star only
for(int star=1; star<=row;star++){
cout<<"*"<<"";
//print row
cout<,"\n"; OR cout<<endl;
}

29
for loop is equivalent to
while loop
• Used when a loop
for (expr1; expr2; expr3)
is to be executed a
{
known / fixed
action
} number of times.
We can do the
same thing with a
expr1;
while (expr2) while loop, but the
{ for loop is easier to
action; read and more
expr3; natural for counter-
} controlled loops.
30
for loop is equivalent to
while loop
for loop while loop

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


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

31
for loop
The empty for statement causes
an endless loop

for ( ; ; )
{
action;

The loop can start but no condition tells


when to end the loop
32
for loop - Exercise
• Write a for loop to print the following integers
in sequence:
5 10 15 20 25 30 35 40 45 50

Answer:
for ( i = 5; i <= 50, i+=5 )
cout << i << ‘ ’;

33
for loop - Exercise
• Write a program that Answer:
reads a number, and
int limit;
use a for loop to
cout << “Please enter the
display series of limit : ";
integers from 1 up to cin << limit;
the number. The
output should be:
for (i = 1; i <= limit; i++)
Please enter the limit : 3 {
1 cout << i << endl;
2 }
3
34
do-while loop
• It is a post-test and event-controlled loop.
• If you want the loop’s body to execute at least
1 time, you can use a do-while loop.

do
Actions {
action;
true
Condition } while (condition);

false
35
do-while loop – Exercise
• Convert the following loops to do-while loops.
The output should remain the same.

(a) Print the square of integers 1 to 10 inclusive.


number = 1;
while (number <= 10)
{
square = number * number;
cout << square << ‘ ’;
number++;
}
36
do-while loop – Exercise
Answer:
number = 1;
do {
square = number * number;
cout << square << ‘ ’;
number ++;
} while (number <= 10);

37
do-while loop – Exercise

(b) Print all multiple of 3 in between 10 to 90 inclusive.


for (num = 10; num <= 90; num++)
{
if (num % 3 == 0)
{
cout << num << ‘ ’;
}
}

38
do-while loop – Exercise
Answer:
num = 10;
do {
if (num % 3 == 0)
cout << num << ‘ ’;
num ++;
} while (num <= 90);

39
Loop used to
Accumulate Total assignment

• An accumulator is a variable that you use to


gather or accumulate values.
• Important: Accumulator has initial value.
Usually it starts with 0.
Total Sales

Product 1: 120
Product 2: 250
Product 3: 360
Product 4: 99

Total: 829
40
Loop used to
Accumulate Total
• Example:
int total = 0, price;

for(int i = 0; i<4; i++) accumulator


{
cout << "Product " << i+1 << ": -> ";
cin >> price;
total = total + price;
}

cout << "\n\nTotal: " << total << endl;


41
Nested Loop
• Loop within a loop.
• Program logic gets more complicated.
• When there is a nested loop, for each iteration
of the outer loop, the inner loop is entered and
repeated until done before the next outer loop
is entered.

42
Nested Loop - Example
for(i=0; i<3; i++)
Output: {
i=0: 1 2 3 4 5 cout<<“i=”<<i<<‘: ’;
i=1: 1 2 3 4 5
for(j=1; j<=5; j++)
i=2: 1 2 3 4 5 cout << j;

cout << endl;


}

43
Nested Loop – Exercise

• Use nested for loop to Answer:


print the pattern below: for (i = 0; i <= 3; i++)
@@@@@ {
for (j = 0; j <= 4; j++)
@@@@@
cout << ‘@’;
@@@@@
@@@@@ cout << endl;
}

44
Nested Loop – Exercise
• Without using the aid of computer, produce the
output of the following code:

int i, j;
for (i = 1; i <= 3; i++)
{
cout<<"Outer “<<i<<endl;
for (j = 1; j <= i; j++)
{
cout<<"Inner “<<j;
cout<<endl;
}
}
45
Nested Loop – Exercise
• What is the output for the following code?
for(int x = 0; x < 4; x++)
{
for(int y = 0; y <= x; y++)
{
cout << “+” ;
}
cout << endl;
}
46
Jump Statements
• To terminate the loop or skip some statements
within a loop when certain condition is TRUE.
• Some controls of loop execution are needed.
• 2 types of jump statements:
• break statement
• continue statement

47
break statement
• Causes immediate exit from the structure .
• Program execution continues with the first
statement after the structure.
• It can be used in
− while loop
− for loop
− do-while loop
− switch statement

48
break statement - Example

int x;
for (x = 1; x <= 10; x++)
{
if (x == 5)
break;
cout << x;
}
cout<<“\nLoop ended at ”<<x<<“\n”;

49
continue statement
 A continue statement will skip any remaining
statements in the body of the structure and
proceeds with the next iteration of the loop.
• It can be used in
− while loop
− for loop
− do-while loop

50
continue statement - Example

int x;
for (x = 1; x <= 10; x++)
{ skip 5 and continue the next integer

if (x == 5)
continue;
cout << x;
}
cout<<“\nLoop ended at ”<<x<<“\n”;

51

You might also like