Csc-113 Computer Programming
Csc-113 Computer Programming
LECTURE 06
LOOP STRUCTURE (FOR, WHILE, DO-WHILE)
1
TYPES OF CONTROL STRUCTURES
1. Sequential structure
Processes one instruction after another
How?
1.Cut and paste the codes 160 times?
2.cout << 1 + 2 + +100 << endl; ??
3.Then, what about summing up 1~10000?
CONCEPT OF LOOP
void main(void)
{
int num;
19
Program Output
20
WHILE LOOP
Loop is very important in every programming language that saves you
from repetitive nature of work.
The C++ supports While, do while, and for loop.
The while loop is one of the important looping construct, that is being
widely used in C ++ programming language.
To understand the concept of while loop, consider the following
diagram.
WHILE LOOP
In the example, three things are important.
(i) Initialization
(ii) Increment/Decrement
(iii) Termination
These are the important characteristics of any
loop. Initialization represents the starting
position from there your loop will be started.
In the above example int i=0 refers to
initialization of while loop. i++ refers to
increment/decrement and finally while(i<10)
refers to the termination of while loop.
Each time the while loop executed, it checks
for condition whether the value of i is less
than 10 or not. If the value of i is less than 10,
the loop will be executed and increment i by
one and then print the value of i. When the
value of i reaches 10, the while(i<10)
condition becomes false and terminates the
loop.
WHILE: HOW IT WORKS?
WHILE LOOP
WHILE LOOP HOW IT WORKS?
EXAMPLE (01)
DO WHILE
DO WHILE
do while loop treats same as while loop but only differences between
them is that, do while executes at least one time.
The code executes first then check for specified loop condition. But in
while loop, the specified loop condition evaluated first then executes
the code.
A simple demonstration will help you to figure out do while loop more
clearly.
DO WHILE
Note: You must put semi-colon(;) at the end of while condition in dowhile loop.
DO WHILE: HOW IT WORKS?
DO WHILE: HOW IT WORKS?
DO WHILE LOOP
DO WHILE: HOW IT WORKS?
NESTED LOOP
Sometimes, you are required to perform a task in nested loop
condition.
A loop within a loop is called nested loop.
You can nested n number of loop as nested.
NESTED LOOP
In the preceding example, the outer for loop wont
increment until inner for loop processes its all the cycles.
Once the condition of inner for loop becomes false, the
outer for loop increment by one and then again inner for
loop does same work as previous.
NESTED LOOP
NESTED LOOP: HOW IT WORKS?