ReinhardKomansilan
10 views
16 slides
Oct 16, 2024
Slide 1 of 16
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
About This Presentation
Lecture about nested loops
Size: 128.3 KB
Language: en
Added: Oct 16, 2024
Slides: 16 pages
Slide Content
Intro to Programming
Week # 6
Repetition Structure
Lecture # 10
By: Saqib Rasheed
Department of Computer Science & Engineering
Air University
.
Nested loops
Nested Loops
•A loop can be nested inside of another loop.
•C++ allows at least 256 levels of nesting
•When working with nested loops, the outer
loop changes only after the inner loop is
completely finished
The syntax for a
nested for
loop
statement in C++
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a
nested while
loop
statement in C++
while(condition)
{
while(condition)
{
statement(s);
}
statement(s); // you can put more statements.
}
The syntax for a
nested
do...while loop
statement in C++
do {
statement(s); // you can put more statements.
do {
statement(s);
}
while( condition );
}
while( condition );
For loop nesting
8
Nested loops (loop in loop)
cin >> a >> b;
for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
cout << “*”;
}
cout << endl;
}
*************
*************
*************
*************
b
a
9
Nested loops (2)
int a,b;
cin >> a >> b;
for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
if (j > i)
break;
cout << “*”;
}
cout << endl;
}
*
**
***
****
b
a
10
Nested loops (3)
*
**
***
****
b
a
int a,b;
cin >> a >> b;
for (int i = 0; i < a; i++)
{ for (int j=0; j<b && j < i; j++)
{
cout << “*”;
}
cout << endl;
}
j <= i;
if (j > i) break;
11
Nested loops (4)
int a,b;
cin >> a >> b;
for (int i = 0; i < a; i++)
{
for (int j=0; j<b; j++)
{
if (j < i)
cout << “ ”;
else
cout << “*”;
}
cout << endl;
}
*************
************
***********
**********
b
a
.
Develop a code in C++ that generate the
following series .Use nested while loop!
Air University
1
1 2
1 2 3
1 2 3 4
1
2 2
3 3 3
4 4 4 4
1
2 3
4 5 6
7 8 9 10
Series
No. 1 No. 2 No. 3