You are on page 1of 13

Mathematics & Computer

Programming

Toqeer Mahmood
Dept. of Civil Engg.
UET, Taxila
The “for” Loop
“for” loop is used to execute a set of statements
repeatedly for a fixed number of times.
It is also known as a counter loop.
Syntax:
for(initialization; condition; increment/decrement)
Statement;

for(initialization; condition; increment/decrement)


{
Statement/s; (Body of the loop)
}
The “while” Loop
It is a conditional loop statement.
It is used to execute a statement or a set of statements as
long as the given condition remains true.

Syntax:
while (condition)
statement;

while (condition)
{
statement(s);
}
The “do-while” loop
The “do-while” loop is also a conditional loop
statement.
It is like a while loop, but in this loop the condition is
tested after executing the statements of the loop.

Syntax:

do
{
statement/s ;
}
while (condition);
Lecture
#
08
Nested Loops
Loop/s inside the loop is known as Nested
Loop
Nested “for” Loop
Syntax:
for(initialization; condition; increment/decrement)
{
Statement/s;

for(initialization; condition; increment/decrement)


{
Statement/s; (Body of the loop)
}

Statement/s;
}
Nested “while” Loop
Syntax:
while (condition)
{
Statement/s;

while (condition)
{
statement/s;
}

Statement/s;
}
Nested “do-while” loop
Syntax:
do
{
Statement/s;

do
{
statement/s ;
}
while (condition);

Statement/s;
}
while (condition);
Program
#include<conio.h>
#include<iostream.h>
void main()
{
clrscr();
int n, r;

for(int i=1 ; i<=3 ; i++)


{
for(int j=1 ; j<=3 ; j++)
cout<<“This lecture is about Nested loops”;
}

getch();
}
Program
Write a program to print the output as shown below
* #include<conio.h>
* * #include<iostream.h>
* * * void main()
* * * * {
* * * * * clrscr();
* * * * * * int i, j;

for(i=1 ; i<=6 ; i++)


{
for(j=1 ; j<=i ; j++)
cout<<“ * ”;

cout<<endl;
}

getch();
}
Program
Write a program to print the output as shown below
* #include<conio.h>
*** #include<iostream.h>
***** #include<iomanip.h>
******* void main()
{
clrscr();
int s, i;

for(s=20, i=1 ; i<=10 ; i+=2 , s - -)


{
cout<<setw(s)

for(int j = 1 ; j <= i ; j++)


cout<<“ * ”;
cout<<endl;
}

getch();
}
Lab work
Write a program to print the output as shown below using while or do-while loop
*
* *
* * *
* * * *
* * * * *
* * * * * *

Write a program to print the output as shown below using while or do-while loop
* * * * * *
* * * * *
* * * *
* * *
* *
*
Write a program to print the output as shown below using while or do-while loop

*******
*****
***
*

You might also like