CP Unit 2
CP Unit 2
ENGINEERING COLLEGE
(AUTONOMOUS | VISAKHAPATNAM)
• Here, initially, the condition (i <= 10) is true. After each iteration of
the loop, the value of 'i' increases. When the value of 'i' equals 11, the
condition becomes false, and the loop terminates.
Introduction to Programming Raghu Engineering College (A) 24
b) do while loop:
• The 'do...while' statement is also used for looping. The body of this loop
may contain a single statement or a block of statements.
• The syntax for writing this loop is:
do
{
Body of loop;
-----
} while(condition);
Next statement out of loop;
• Here, firstly, the statements inside the loop body are
executed, and then the condition is evaluated. If the
condition is true, then again the loop body is executed, and
this process continues until the condition becomes false.
• Note that, unlike the while loop, here a semicolon is
placed after the condition.
Introduction to Programming Raghu Engineering College (A) 25
Example: Program to print the numbers from 1 to 10 using do while loop
• Generally while loop is used more frequently than the do while loop
but some situations may arise when it is better to check the condition
at the bottom of loop.
Introduction to Programming Raghu Engineering College (A) 26
Class Exercises:
1. Write a C program to print numbers from 1 to 10.
2. Write a C program to find sum of digits of any number
3. Write a C program to print numbers from 1 to 20 with a difference of 2
(Example:1 3 5…)
Initialization expression;
while(condition)
{
Body of loop;
Update expression;
}
Here for each iteration of the outer loop, the inner loop is executed 4 times.