Loops in Cpp

Loops in Cpp


What is Loop ?

Looping is nothing but defined as repeating the same process many times until a particular condition satisfied. A Loop consists of two parts, body of a loop and a control statement.

In this tutorial you will learn :


Why do we need Loops ? 

1. Repeating the same condition for a finite number of times.
2. Simplifying the complex problems into the easy ones.

Types of Loop :

Depending upon the position of a control statement in a program, loops are classified into two types.

1. Entry Controlled Loop :

A condition is checked before entering the loop body. It is also known as Pre-Checking Loop. for loop and while loop are entry controlled loops.

2. Exit Controlled Loops :

A condition is checked after executing the body of the loop. So, the loop body will execute at least once, wheather the condition is true or false. It is also known as Post Checking Loop. The do-while loop is exit controlled loop.

There are mainly three types of loop in C++ Programming Language.
1. Do while Loop
2. While Loop
3. For Loop

Advantage of loops :

1. Traverse over the elements of array or linked list by using loop.
2. Do not have to write the same code again and again.
3. Code's re-usage is made by using of loop.

While Loop :

When the number of iteration is unknown then the while loop is used. While loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It is completed in 3 steps.

1. Variable initialization. (e.g int P = 0;)
2. Condition (e.g while (P <= 3))
3. Increment or decrement (P++ or P--)

Syntax :
while(condition)
{
// statement;
}

Sample Program :
//C program to illustrate while loop.

#include<iostream>
using namespace std;
int main()
{
int P = 0;  //variable initialization
    while (P < 4)  //test expression
    {
    	cout<<"Eruditors" <<endl;  
        P++;  //increment
    }
    return 0;
}

//P is intialized to 0.
//When P is 0, the expression P < 4 is true. Hence the body of the loop is executed.
//This will print Eruditors on the screen and the value of P is increased to 1(because of P++).
//Now, P is 1 and the expression P< 4 is true again. So, the body of the loop will be executed.
//Again this will print Eruditors in a new line(because of \n) on the screen and the value of P is increased to 2(because of P++)
//This process will go on until P becomes 4. And then the expression P < 4 will be false and the loop will be terminated.


Output :
Eruditors
Eruditors
Eruditors
Eruditors

Related Program : 

Fibonacci Series program in C++

C++ Program to find Sum and Average of N Natural Numbers 

 

Do while loop :

The do-while loop is mainly used in the case where we need to execute the loop at least once. We can repeat the execution of several part of statements by using do-while loop. It's mostly used in menu-driven programs.

Syntax :
do
{
//Statements;
}
while(condition);

Sample Program :
//C program to illustrate do while loop

#include<iostream>
using namespace std;
int main ()
{
	int p = 5; //variable initialization.

    do
    {
    	cout << "p = " <<p <<endl;
        p++;
    }
    while( p < 8 );  //test expression.
    return 0;
}

//Variable p is initialized to 5. Then the do-while loop has started.
//In the loop body the cout function will 1st print 5 and then p will be incremented by 1. Now, the value of p is 6.
//This will go on until the value of p becomes 7 because of p < 8 expression. Then the loop will be terminated when p becomes 8. 


Output :
p = 5
p = 6
p = 7

For Loop :

The loop which we used to statements of a program several times is known as For loop. It is used to traverse over the elements of array and linked lists.

Syntax :
for(initialization statement ; test Expression ; increment or decrement)
{
	//statement;
}

Sample Program :

#include<iostream>
using namespace std;
int main ()
{
    int a;
    for( a = 5; a < 8; a++ )
    {
    	cout <<"a = " << a <<endl;
    }
	return 0;
}

//1. It first evaluates the initialization variable a to 5.
//2. Then it checks the condition a < 8;
//3. If the condition is true, then it executes the for-loop body. Here, it will print 5.
//4. Then it increment the value of a because of the increment condition. Now, the value of a will become 6.
//5. After that it will again follow from step 2. When the expression becomes false, the loop will be terminated.

Output :
a = 5
a = 6
a = 7

Related Program :

Nested For Loop :

You can also have one for loop inside another for loop, which is known as Nested for loop. In nested for loop there is an outer loop and an inner loop. For each iteration of the outer loop, the inner loop repeats its entire cycle.

Syntax :
for(initialization statement ; test Expression ; increment or decrement)
{
	for(initialization statement ; test Expression ; increment or decrement)
    {
    	Statement;
    }
}

Sample Program :
//Program to print half Pyramid of numbers.

#include<iostream>
using namespace std;
int main ()
{
int i,j,row;
cout << "enter the row number : ";
cin >> row;
/* first for loop as well as outer for loop */
for(i=1;i<=row;i++)
{
/* second for loop or inner for loop inside the first for loop */
for(j=1;j<=i;j++)
{
cout << j;
}
cout <<"\n";
}
}

Output :


Related Program :

Infinite Loop :

A loop which lacks a functional exit and started repeating infinitely, is known as the Infinite Loop. When a conditional expression is absent it always evaluates to be true and then it turns into an infinite loop. Basically infinite loop is an error.

Sample Program :

#include <iostream>
using namespace std;
int main ()
{
    int a;
    for( ; ; )	//expression is black & will lead to an infinite loop 
    {
    	cout <<"May your parents live long !!" <<endl;
    }
	return 0;
}

Output :


This is just a part of the output screen. The infinite loop can be terminated by pressing Ctrl+C keys.

Comparison between Loops :

while and do while loop :

1. While loop is an entry controlled loop.
~ But do while loop is an exit controlled loop.
2. While loop checks the condition when the loop started and if the condition became satisfied the loop's statement is being executed. 
~ But in case of the do-while loop, the condition is checked after the execution of all statements in the body of the loop.
3. In case of while loop not a single statement inside the loop is executed when the condition is false. 
~ But if the condition in ‘do-while’ loop is false, then also the body of the loop is executed for minimum one time then the condition is tested.

while and for loop :

1. Condition is relational and non zero both for while loop where for loop stands for relational condition.
2. In case of while loop we don't know the total number of iterations.
~ But in case of for loop we know the total number of iterations.
3. After executing the statement, the increment is surely done for for loop.
~ But in case of while loop the increment is done before or after executing the statements.
4. In while loop Initialization happens outside the loop where in case of for loop initialization happens in both inside and outside.
5. Both these loops are entry controlled loop.

do while and for loop :

1. do-while is an exit controlled loop where for loop is an entry control loop.
2. In do- while statement is executed at least once where in case of for loop statement executed zero times.
4. In both case initialization happened both inside and out side.
5. 1st executed the statement and then check the condition in do while loop where in for loop to execute the statement condition has been checked.