7-11 Dec Lectures
7-11 Dec Lectures
Statements
Why Is Repetition Needed?
4
The while Loop (continued)
5
The for Loop
statement
9
for (initial statement; loop condition; update statement)
15
Using for Loop, add first 10 positive even
integers.
#include <iostrem>
Using namespace std;
Int main() Sum=0+2+4+6+8
+10+12+14+16+
{ 18
int i, sum; Sum=90
for (i=0;i<20;i=i+2)
{
sum+=i;
}
cout<<sum<<endl;
Return 0;
}
17
The do…while Loop
18
The do…while Loop (continued)
19
Write program to add first 10 even
integers using do while loop
#include <iostream>
Using namespace std;
Int main()
{
int i=0, sum;
do
{
sum+=i;
i=i+2;
}
While(i<20);
cout<<sum<<endl;
Return 0;
} 23
break & continue Statements
25
break & continue Statements
(continued)
• continue is used in while, for, and do…
while structures
26
break & continue Statements
(continued)
• In a while and do…while structure
27
Nested Control Structures
28
Nested Control Structures
(continued)
• Since five lines are to be printed, we start
with the following for statement
for (i = 1; i <= 5 ; i++)
29
Nested Control Structures
(continued)
• The syntax is:
for (i = 1; i <= 5 ; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
30
Nested Control Structures
(continued)
• What pattern does the code produce if we
replace the first for statement with the
following?
for (i = 5; i >= 1; i--)
• Answer:
*****
****
***
**
*
31
Summary
32
Summary (continued)
• while: expression is the decision maker, and
the statement is the body of the loop
• In a counter-controlled while loop,
− Initialize counter before loop
− Body must contain a statement that changes the value
of the counter variable
• A sentinel-controlled while loop uses a
sentinel to control the while loop
33
Summary (continued)
• for loop: simplifies the writing of a count-
controlled while loop
• Executing a break statement in the body of a
loop immediately terminates the loop
• Executing a continue statement in the body
of a loop skips to the next iteration
• After a continue statement executes in a for
loop, the update statement is the next
statement executed
34