Week 05
Week 05
COMPUTER PROGRAMMING
Muzammil Ahmad Khan
[email protected]
Loop Mechanism
2
Objectives
3
Objectives
4
Why Is Repetition Needed?
10
The while Loop
13
The while Loop
14
Counter-Controlled while Loops
15
Counter-Controlled while Loops
16
Counter-Controlled while Loops
• If you know exactly how many pieces of data need to be read, the
while loop becomes a counter-controlled loop
17
Counter-Controlled while Loops
• In this example, while loop increments the value of i by three every iteration.
The loop terminates when the value of i exceeds 12.
#include <iostream>
using namespace std;
int main() {
int i=0;
while (i<=12)
{
cout<<i<<"\t";
i += 3; }
cout<<endl;
}
18
Sentinel-Controlled while Loops
19
Sentinel-Controlled while Loops
20
Sentinel-Controlled while Loops
21
Flag-Controlled while Loops
22
Flag-Controlled while Loops
25
The for Loop
The initial statement usually initializes a variable (called the for loop control, or for
indexed, variable).
In C++, for is a reserved word.
26
The for Loop
27
The for Loop
28
The for Loop (comments)
29
The for Loop (comments)
30
The for Loop (comments)
31
The for Loop (comments)
32
The do…while Loop
33
The do…while Loop
34
The do…while Loop
36
break & continue Statements
37
break & continue Statements
38
break & continue Statements
40
Nested Control Structures
• What pattern does the code produce if we replace the first for statement with
the following?
• Answer:
*****
****
***
**
*
42
Summary
43
Summary
− Body must contain a statement that changes the value of the counter variable