Today We Will Cover: For Loop Nested Loop
Today We Will Cover: For Loop Nested Loop
For Loop
Nested Loop
For Loop 2
When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been
executed
For Loop 3
Example
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed
For Loop 4
Another Example
Output ???
Task 5
Nested Loops
Nested Loop 10
int main()
{
for(int i=1; i<=5; i++)
Output
{ 1
for(int j=1; j<=i; j++) 12
123
{
1234
cout<<j; 12345
}
cout<<"\n";
}
return 0;
}
Nested Loop 11
int main()
{
for(int i=5; i>=1; i--)
{
for(int j=i; j>=1; j--) Output
{ 54321
4321
cout<<j;
321
} 21
cout<<"\n"; 1
}
return 0;
}
Nested Loop 12
int main()
{
for(int i=5; i>=1; i--)
{
for(int j=1; j<=i; j++)
{ Output
12345
cout<<j; 1234
} 123
12
cout<<"\n";
1
}
return 0;
}
Nested Loop 13
int i=5;
while(i>=1)
{
int j=1;
while(j<=i)
{
Output
Cout<<j; 12345
j++; 1234
123
}
12
i--; 1
Cout<<“\n”;
}
Nested Loop 14
for(int i=5;i>=1;i--)
{
for(int j=1;j<=i;j++)
{
Cout<<“*”;
} Output
*****
Cout<<“\n”;
****
} ***
**
*
15
Output
*
**
***
****
*****
Now lets try a real world example of nested 16
for loop.
Write a program using for, while and do while and nested loops to display the
following outputs.
12345678910 1 *
123456789 12 ======
***
12345678 123 *********
*****
1234567 1234 *******
*******
123456 12345 *****
*******
12345 123456 ***
*****
1234 1234567 *
***
123 12345678 ======
*
12 123456789
1 12345678910
22
Programs: 23
Write a program using for, while and do while and nested loops to display the
following outputs.
13579 0 &
13579 02 && *
1357 024 &&& ***
1357 0246 &&&& *****
135 02468 &&&&& *******
135 0246810 &&&&& *****
13 024681012 &&&& ***
1 02468101214 &&& *
&&
&