Iterative Statement
Iterative Statement
Iterative Statement
An iterative statement, or loop, is a control structure used to repeat a set of instructions until
a specific condition is met. Iterative statements are essential in programming because they
allow us to automate repetitive tasks efficiently.
Each type has its unique use case, which we will explore with examples.
Iterative Statement
A for loop is ideal when the number of iterations is known beforehand. It consists of three parts:
Syntax:
for (initialization; condition; update) {
// Code to execute repeatedly
}
Iterative Statement
Explanation
A while loop is used when the number of iterations is not known and depends
on a condition that must remain true. It checks the condition before executing
the loop body
Syntax:
while (condition) {
// Code to execute repeatedly
}
Iterative Statement
int number = 1;
while (number <= 100) {
cout<<number<<“\n”;
number = number * 2; // Double the number
}
Explanation:
• The loop checks number <= 100 before each iteration.
• If true, the body executes, doubling the value of number.
• Once number > 100, the loop exits.
Iterative Statement
A do-while loop is similar to the while loop but with one key difference: it guarantees that the
loop body executes at least once, regardless of the condition.
Syntax:
do {
// Code to execute repeatedly
} while (condition);
Iterative Statement
int number;
do {
cout<<Enter a positive number:;
cin>>number;
} while (number <= 0);
Iterative Statement
Explanation:
COMPARISON OF LOOPS
Guaranteed one
Use Case Known iterations Unknown iterations
execution
• Use a for loop when you know how many times the loop should run.
• Use a while loop when the end condition depends on dynamic
inputs or changes during runtime.
• Use a do-while loop when you want the body to execute at least
once, regardless of the condition.
Iterative Statement
Interactive Exercise
1. Write a program using a for loop to print all even numbers between 1 and
20.
2. Modify the program to use a while loop instead.
3. Use a do-while loop to validate user input for a number in the range 1-50.
Thank You