on Leave a Comment

C++ looping - for loop, while loop, do while loop

C++ looping concept is similar to C looping concept. Looping is required when you want to execute some set of statements repeatedly, until a particular condition is satisfied.

HOW DOES A LOOP WORK ?

C++ looping

When c++ compiler comes into loop, first it checks condition, if condition is satisfied, it executes sets of statements in loop body. After executing set of statements in loop body, compiler again checks condition, and if again condition is satisfied, compiler again executes set of statements in loop body. Compiler repeatedly executes set of statements in loop body, until condition is unsatisfied.

TYPES OF LOOPS IN C++ LANGUAGE

  • for loop
  • while loop
  • do-while loop

for loop

for loop is a loop that executes set of statement  repeatedly until particular condition is satisfied. for loop is most popular loop.

SYNTAX OF FOR LOOP

for(<initialization>;<condition>;<increment/decrement>)
{
     //for loop body
}

EXAMPLE OF FOR LOOP

for(i=0;i<5;i++)
{
      cout<<"C++ programming"<<endl;
}

OUTPUT:
C++ programming
C++ programming
C++ programming
C++ programming
C++ programming


while loop

while is a keyword in c++ language. 

SYNTAX OF WHILE LOOP

variable initialization;
while(condition)
{
     //while loop statements
     variable increment/decrement;
}

EXAMPLE OF WHILE LOOP

int i=0;
while(i<5)
{
      cout<<"C++ programming"<<endl;
      i++;
}

OUTPUT:
C++ programming
C++ programming
C++ programming
C++ programming
C++ programming


do while loop

do and while are keywords in c++ language. In do-while loop, at first time do-while statements are always executing because condition will check after statements.

SYNTAX OF DO WHILE LOOP

variable initialization;
do
{
     //do while loop statements
     variable increment/decrement;
}
while(condition);

EXAMPLE OF DO WHILE LOOP

int i=0;
do
{
      cout<<"C++ programming"<<endl;
      i++;
}
while(i<5)

OUTPUT:
C++ programming
C++ programming
C++ programming
C++ programming
C++ programming


0 comments:

Post a Comment