Chapter 5-Control Loops
Chapter 5-Control Loops
Control Loops
OBJECTIVES LEARNING OUTCOMES (LO)
7. Explain and apply the control 2. Write a C program, compile it,
structures use in C-programming link it, execute it and debug it.
such as if statement, if else 7. Implements Loop structures in
statement, switch statement, and C.
looping/iteration statements. 12. Recognize a program written
9. Capable of designing and in C.
implementing C programs to solve 13. Solve a simple real world
simple and complex problems problems by using programming
in C.
1
•Loops are used in programs to repeat
the execution of a part of a program for a
number of times.
2
5.1 while Loop:
•It is useful when we don’t know in
advance how many times the loop will
repeat.
Syntax:
while ( condition)
{
Simple or Compound Statement;
}
3
•First the condition is checked. If it is
true, then the body of loop is executed.
•After completing execution of the loop
once, again the condition will be checked.
If it is still true then again the body will be
executed.
•The loop will stop when the condition
becomes false. The program will continue
from the statement next to the loop body.
4
•The condition must have an initial value
before the start of while loop.
17
18
19
5.3 for Loop:
Syntax:
for (initialization ; condition; increment /decrement )
{
Simple or Compound Statement;
}
The execution of for loop is performed according to
the following sequence:
1. The initialization statement is executed only for
one time at the start of the loop.
One or more variables (like the counter of the loop)
will be initialized to certain values. 20
2. The condition will be tested. If it is true the
body of the loop will be executed. If it is false,
the body of the loop will not be executed and
the loop will terminate.
3. The increment/decrement statement will
be executed after executing the body of the
loop. In this part one or more variables will be
incremented or decremented by certain
values.
After that again the program will return to
check the condition. If it is true, again the
body of the loop will be executed and so on. 21
Flowchart of for loop:
22
23
24
25
26
27
28
5.4 Nesting of Loops:
Nesting of loops means one loop will be inside
another loop.
Example: nesting of two for loops:
29
For each one count of the outer for loop, the inner
for loop will repeat its count from start up to end.
30
31