2. Rushdi Shams, Dept of CSE, KUET, Bangladesh2
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.
9. Rushdi Shams, Dept of CSE, KUET, Bangladesh9
Variation of for loop: Infinite
loop
10. Rushdi Shams, Dept of CSE, KUET, Bangladesh10
Observing for loops
The initialization, loop-continuation
condition and increment/decrement can
contain arithmetic expressions. Assume
that 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)
11. Rushdi Shams, Dept of CSE, KUET, Bangladesh11
Observing for loops
There can be a decrement as well (or you
can say a negative increment). For
example-
12. Rushdi Shams, Dept of CSE, KUET, Bangladesh12
Observing for loops
If the loop continuation condition is initially
false, the body portion of the loop is not
performed.
19. Rushdi Shams, Dept of CSE, KUET, Bangladesh19
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.
20. Rushdi Shams, Dept of CSE, KUET, Bangladesh20
The break Statement
When break is encountered inside any
loop, control automatically passes to the
first statement after the loop.
22. Rushdi Shams, Dept of CSE, KUET, Bangladesh22
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.
23. Rushdi Shams, Dept of CSE, KUET, Bangladesh23
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.