Download - C-06
Lecture 6Version 1.0
The for LoopThe break Statement
The continue StatementVersion 1.0
Rushdi Shams, Dept of CSE, KUET, Bangladesh
2
The for Loop
The for loop allows us to specify three things in a single line:
1. Setting a loop counter to an initial value.2. Testing the loop counter to determine whether its
value has reached the number of repetitions desired.3. Increasing/decreasing the value of loop counter each
time the program segment within the loop is executed.
Rushdi Shams, Dept of CSE, KUET, Bangladesh
3
General form of for loop
Rushdi Shams, Dept of CSE, KUET, Bangladesh
4
Example of for loop This program prints number 1 to 10
Rushdi Shams, Dept of CSE, KUET, Bangladesh
5
Structure of for loop
Rushdi Shams, Dept of CSE, KUET, Bangladesh
6
Variation of for loop
Rushdi Shams, Dept of CSE, KUET, Bangladesh
7
Variation of for loop
Rushdi Shams, Dept of CSE, KUET, Bangladesh
8
Variation of for loop
Rushdi Shams, Dept of CSE, KUET, Bangladesh
9
Variation of for loop: Infinite loop
Rushdi Shams, Dept of CSE, KUET, Bangladesh
10
Observing for loops
The initialization, loop-continuationcondition and increment/decrement cancontain arithmetic expressions. Assumethat x=2 and y=10. The statement-for(j=x; j<=4*x*y; j=j+y/x)
is equivalent to-for(j=2; j<=80; j=j+5)
Rushdi Shams, Dept of CSE, KUET, Bangladesh
11
Observing for loops
There can be a decrement as well (or you
can say a negative increment). Forexample-
Rushdi Shams, Dept of CSE, KUET, Bangladesh
12
Observing for loops
If the loop continuation condition is initially
false, the body portion of the loop is notperformed.
Rushdi Shams, Dept of CSE, KUET, Bangladesh
13
Observing for loops
Rushdi Shams, Dept of CSE, KUET, Bangladesh
14
Qs
Rushdi Shams, Dept of CSE, KUET, Bangladesh
15
Nested for loops
Rushdi Shams, Dept of CSE, KUET, Bangladesh
16
Output
Rushdi Shams, Dept of CSE, KUET, Bangladesh
17
What will be the output?
Rushdi Shams, Dept of CSE, KUET, Bangladesh
18
What will be the output?
Rushdi Shams, Dept of CSE, KUET, Bangladesh
19
The break Statement
We often come across situations where we want to jump out of a loop instantly, without waiting to get back to the conditional test.
The keyword break allows us to do this.
Rushdi Shams, Dept of CSE, KUET, Bangladesh
20
The break Statement
When break is encountered inside any loop, control automatically passes to the first statement after the loop.
Rushdi Shams, Dept of CSE, KUET, Bangladesh
21
The break Statement
Rushdi Shams, Dept of CSE, KUET, Bangladesh
22
The continue Statement
In some programming situations we want to take the control to the beginning of the loop, bypassing the statements inside the loop, which have not yet been executed.
Rushdi Shams, Dept of CSE, KUET, Bangladesh
23
The continue Statement
The keyword continue allows us to do this. When continue is encountered inside any loop, control automatically passes to the beginning of the loop.
Rushdi Shams, Dept of CSE, KUET, Bangladesh
24
The continue Statement