Chapter 7
Chapter 7
Chapter 7
Introduction to Programming
Chapter 7
Iteration Statements
Introduction to Programming
Learning outcomes:
Iteration Statement
While Loop
Do While Loop
For Loop
Loop Statement
A loop is used for executing a block of statements repeatedly until a
particular condition is satisfied.
Loops come into use when we need to repeatedly execute a block of
statements.
In programming, sometimes there is a need to perform some operation
n number of times.
For example: Suppose we want to print “Hello World” 10 times.
Iteration (loop) Statement
In C++ there are three loop statement as follow:
1. While loop
2. Do while loop
3. For loop
While loop
• In C++, while loop is used to run a part of the program several times
until certain condition is met.
• It first check the condition and if the value of condition is true it will
execute the statement followed by while loop.
• And every time the value of expression is increased or decreased and
condition is checked and the same statement will be executed
repeatedly until the condition become false.
While loop
while (condition)
{
// statements
//update expression;
}
While Loop Example
// program to print numbers from 1 to 10 using while loop
#include <iostream>
using namespace std;
int main()
{
int i = 1;
while ( I <= 10)
{
cout << i << endl;
i++;
}
}
Do While loop
• In C++, do while loop is used to run a part of the program several
times until certain condition is met.
• It first run the statement and then check the condition and if the value
of condition is true it will display the result and if the value of condition
is false it will stop the execution.
• And every time the value of expression is increased or decreased and
condition is checked until the condition become false.
Do While loop
Do While syntax:
do
{
//code to be executed
//update expression;
}
while (condition);
Do While Example
#include <iostream>
using namespace std;
int main() {
int i = 1;
do{
cout<< I <<endl;
i++;
}
while (i <= 10) ;
}
For loop
The C++ for loop is used to iterate or
run a part of the program several
times.
If the number of iteration is fixed, it is
recommended to use for loop than
while or do-while loops.
For loop
• For loop syntax: