Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere


Loops In C++

Loops are used to repeat a block of code.
Sometime, you come across a suiation, where you want do a perticular task multipletimes until a stop condition arrives. In C++, loops are used to execute a piece of code mupliple time.
C++ has provided three loops to achieve this functionality.

1-For Loop- For loops is the basic and the most useful loop provided by c++.
Syntex-
for(variable initialization; condition; variable update(increment/decrement) )
{
      Code to execute while the condition is true
}

For loop works in three steps-
First, The variable initialization allows you to either declare a variable and give it a value or give a value to an already existing variable.
Second, the condition tells the program that execute the code block till the conditional expression is true.
Third, The variable update section is chnage the variable value.
Notice that semicolon separates each of these sections, and it is important to use it in for loop.
Every section should be present in loop,if the section is empty still the condition should be there.
If the condition is empty, it is evaluated as true and the loop will repeat until something else stops it.

Ex-
For loop

Out Put-
Value of itr variable is=0
Value of itr variable is=1
Value of itr variable is=2
Value of itr variable is=3
Value of itr variable is=4
Value of itr variable is=5
Value of itr variable is=6
Value of itr variable is=7
Value of itr variable is=8
Value of itr variable is=9


2-While Loop-
Syntex-
while ( condition )
{
      Code to execute while the condition is true
}

Ex-
while loop


3-Do-While Loop-
DO..WHILE loops are useful when you want to execute the code block at least once.
do- while loop first execute the code block and then check for the condition.
Syntex-
do
{
      Code to execute while the condition is true
}while ( condition );

Ex-
do while loop