CSC425 Topic 3 Control Structure II
CSC425 Topic 3 Control Structure II
Computer Programming
(CSC425)
3
Introduction
The repetition structure is a section of repeating
codes in a program, which is a loop
The loop contains a set of statements to be
executed repeatedly based on a condition
Three basic types of loops :
for
while
do..while
4
The for loop
The general form of the for statement is:
5
The for loop (cont.)
6
The for loop (cont.)
for (initial statement; loop condition; update statement)
7
The for loop (cont.)
8
The for loop (cont.)
Step 3
cout << i << “ ”; Step 4
false
cout << endl;
i Condition cout << i << “ ”; i++
1 1 <=3 true 1 i=1+2=2
2 <=3 true 2 i=2+1=3
3 <=3 true 3 i=3+1=4
4 <=3 false
9
The for loop (cont.)
Example 2 :
10
The for loop (cont.)
Example 3 :
11
The for loop (cont.)
12
The for loop (cont.)
13
The for loop (cont.)
14
The nested for loop
Loop contained within another loop
Example 4 :
15
The nested for loop (cont.)
Example 5 :
How to display a pattern of numbers like this :
*
* *
* * *
* * * *
* * * * *
16
The nested for loop (cont.)
Example 6 :
How to display a pattern of numbers like this :
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7
1 2 3 4 5 6
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
17
The while loop
Required for repetitive execution that cannot be determined
in advance
The syntax :
while (condition)
statement;
18
The while loop (cont.)
19
The while loop (cont.)
20
The while loop (cont.)
21
The while loop (cont.)
22
The while loop (cont.)
23
The while loop (cont.)
24
The while loop (cont.)
25
The do..while loop (cont.)
do
statement
while (expression);
26
The do..while loop (cont.)
27
The do..while loop (cont.)
28
The do..while loop (cont.)
29
The do..while loop (cont.)
30
‘break’ & ‘continue’ statement
A break statement forces an immediate exit when
executed in a while, for, do while or switch statement
A continue statement skips the remaining statements
in the body of the structure and proceeds with the next
iteration of the loop
31
‘break’ & ‘continue’ statement
32