Loops in C++
Loops in C++
@Muhammad
–For loop
• The “for” loop is used to execute a
statement or set of statements repeatedly
for a specific numbers of times
• This loop is also known as counter loop.
Syntax of for loop
For{initialization;condition;increment/decrement}
{
Statements;
}
Next statement;
@Muhamm
The “for”loop is executed as follows;
1) First initialization part is executed . It is executed only for the first time
When control enters into the loop
Working of
For loop
@Muhamma
Flow chart of for loop
False
intialization
True
Body of loop
Increament/decreament
@Muhammad
While loop
•The “while loop ” is conditional loop structure it is used to
Execute a statement or set of statement as long as the given
condtioin remain true
• This loop structure is used when the programmer does not know in
advance
Syntax of while loop;
While (condition)
{
statement;
}
Next – statement;
@Muhamma
The “for”loop is executed as follows;
•When a “while ”loop statement is executed the condition is
evaluate first
• If the condition is true then body of loop is executed
• After executing the body of loop, the execution control goes back to t
he “while”statement and evaluates the condition again.
•If the given condition is still true , the body of loop is executed again.
This process is repeated.
• When the given condition become false at any stage during
• execution ,the loop is terminated.
@Muhamma
• Our Services
Flow chart of ”while”loop
• Insert the title of your subtitle Here
False
True
Body of loop
Next statement
@Muham
Example of “while ” loop
#include <iostream>
using namespace
std;
int main()
{ int num;
num=1;
while(num<=15)
{if (num%3==0)
cout<<num<<endl;
num=num+1;
}}
@Muhamma
DO WHILE LOOP;
• as while loop ,do while loop is also used to execute a state
ment or set of statement as long as the given condition rem
ains true
• The condition comes after the body of loop
• The condition is evaluate after executing the body of loop
The body of loop must be executed at least once even if
The condition is false
• Semicolon(;) is given after the while (condition)
Syntax of Do while loop;
Initialize
Do {
Body of loop
Updation
}
While (condition) @Muhamma
Flow chart of ”Do while”loop
Body of loop
True
False
Next statement
@Muhamma
Example of “Do while ”
loop
#include <iostream>
using namespace
std;
int main()
{ int i=1; do
{cout<<i<<"\n";i++;}
while (i<=10);}
@Muhamma
Nested loop;
• A nested loop is a loop within a loop, an inner loop within
the body of an outer one.
• How this works is that the first pass of the outer loop triggers
the inner loop, which executes to completion. Then the
second pass of the outer loop triggers the inner loop again.
• This repeats until the outer loop finishes
@Muhamma
Example of “nested”
loop
#include<iostream.h>
#include<conio.h>
Main()
{
Int u,i;
U=1;
While (u<=3)
{
Cout <<u<<endl;
For (i=1;i<=2;i++)
Cout <<“I love Pakistan\n”;
U=u+1;
}
}
@Muhamma