Friday 29 September 2017

Types Of For Loop

In the previous post, we understand how for loop works and three parts of for loop.In this post, I will discuss the types of for loop or in which way you will use for loop.
For loops are mainly two types:

  • Infinite for loop
  • Nested for loop
THE INFINITE FOR LOOP:-
A loop becomes infinite loop if the condition never becomes false. For loop required three parts to run initialization, test expression, and update. if you leave the conditions empty that will make the endless loop.

Syntax:-
#include <iostream>
using namespace std;
 
int main () {
   for( ; ; ) {
      cout<<"This loop will run forever.\n";
   }

   return 0;
}
when the conditional expression is absent, it is assumed to be true. you may use initialization and update expression but most of the
programmers prefer "for(; ;)" to construct an infinite for loop.

NOTE:- you will use CTRL+C to terminate the infinite for loop.
use printf("This loop will run forever.\n"); instead of cout<<"This loop will run forever.\n"; do it yourself and see what happened.

NESTED FOR LOOP:-
The placing of one loop inside the body of another loop is called nesting.In nested for loop, a for loop is present inside the another for loop. 

Syntax:-
for ( initialization; test condition; increment ) {

   for ( initialization; tset condition; increment ) //using another variable{
      statement(s);
   }
 
   statement(s);
}

program to print number in the right triangular pattern:-

#include <iostream>
using namespace std;
int main()
{
    int i,j;
    for(i=1;i<=5;i++)
    {
        for(j=1;j<=i;j++)
            cout<<j;
            cout<<"\n"; 
    }
    return 0;
}
Output:-
1
12
123
1234
12345

now take a look how nested loop works? the outer for loop start working,i=1 then it will compare to test condition 1<=5 if the condition is true then it will go to inner for loop and give an increment. In inner for loop j=1, and test condition is 1, i is 1 and j<=i now it will run once and exist from inner for loop and go to outer for loop.Next time i become 2 outer for loop will run once but inner loop will run twice.The process will repeat again and again whenever test condition does not become false.
    
    happy coding....keep learning.

0 comments:

Post a Comment