Chapter 7

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 16

Faculty of Computer Science

Introduction to Programming

Lecturer: Lutfullah “Haqnesar”


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 loop syntax:

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

// program to print numbers from 1 to 10 using do while loop

#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:

for (initialization; condition; incr/decr)


{
//code to be executed
}
For loop
#include <iostream>
using namespace std;
int main()
{
for(int i=1; i<=10; i++)
{
cout<<i <<endl;
}
}
Nested For Loop Example
#include <iostream>
using namespace std;
int main ()
{
for (int i=1; i<=3; i++)
{
for(int j=1; j<=3; j++)
{
cout<< i<<" "<< j<<endl;
}
}
}

You might also like