C++ Loops

October 03, 2015 Posted by WithU Technologies

While Loop:

· While loop executes a statement repeatedly unless and until the condition is fulfilled.

· When the condition is found to be true, at that time the loop stop itself.
Format:

while (condition){

statement;

increment/decrement;

}

Example:

#include <iostream>
using namespace std;

int main(){

int a=1; //Here we initialize the variable ‘a’ from 1

while(a<6){ //Condition: That the loop runs upto 5 times.

cout<<"This is a while loop."<<endl; //This statement and the loop executes upto 5 iteration

a++; //And it will increment at the rate of 1. Equivalent to a=a+1

  }

}


· After the loop completes 5 iteration, ‘a’ becomes 6, and the condition is evaluated to false and the loops stops running.

· We can use any increment value and we are also free to increment or decrement the variable used in looping.

For Loop:

· For loop is used when we exactly know the number of repetitions. It control the repetition structure and thus help us to write a loop that executes a specific number of times.
Format:

for (variable initialization; condition; increment/decrement) {

statement;

}

Example:

#include <iostream>
using namespace std;

int main(){

int a; //Here we initialize the variable a from 1

for(a=1;a<=6;a++) { // we also directly specify the data type here: for(int a=1;a<=6;a++)

cout<<"Help"<<endl;

}

}



· At first the integer value initialize from 1.

· Then the condition specify that the loop run up to 5 iterations at the rate of 1 increment after each and every loop which is modifiable to a+=10, a-=3 or anything.

· After 5th iteration the condition is found to be false and thus the loop terminated.

Do While Loop:

· In do while loop the statement is defined at the top and the condition is defined at its bottom.

· Thus unlike while loop, it executes at least one time due to predefined statement.
Format:

do {

statement;

}

while (condition);

Example:

#include <iostream>
using namespace std;

int main(){

int x=1; // integer variable initialized

do { // following statement executed first

cout<<"Check later"<<endl;

x+=5; // increment of 5 takes place

}

while (x<20); //condition:

}


· Loop runs 20 times according to the condition given i.e. it displays 4 iterations of "check later" statement.

· After the loop displays 4 iterations of that statement, then it found the condition to be false and hence it will terminate.

· And if the condition never evaluates to be false, then the statement runs forever.