Loop In C++


What is Loop

In programming language loop is sequence of statement that used for repeated of statement until a specific condition not reached.
By the example we can understand in easy way without using loop


#include <iostream>

using namespace std;

int main(){

clrscr();

cout<<“Codeverb.com 1”endl;

cout<<“Codeverb.com 2\n”;

cout<<“Codeverb.com 3\n”;

cout<<“Codeverb.com 4\n”;

cout<<“Codeverb.com 5\n”;

return 0;

}


Output
Codeverb.com 1
Codeverb.com 2
Codeverb.com 3
Codeverb.com 4
Codeverb.com 5

Suppose that you want to print 10,20,100,1000 times then just think it’s possible but very difficult to type or copy paste. By using loop we can print many types only two or three line of code.
There are three types of loop used in c++.


  1. for

  2. while

  3. do while

For Loop In C++

or loop used for executes for a group of statement repetation until condition not reached. First initilize then check print statement and after increment/decrement then check condition and again print statement.

Syntax of for loop in c++


for(initilization;condition;incr/decr)

{

statement/expression;

}


Simple example of for loop in c++
Print Codeverb.com message for 5 times by using for loop


#include <iostream>

using namespace std;

int main(){

int i;

clrscr();

for(i=1;i<=5;i++)

{

cout<<“Codeverb.com %d\n”,i;

}

return 0;

}


Output
Codeverb.com 1
Codeverb.com 2
Codeverb.com 3
Codeverb.com 4
Codeverb.com 5

Just look here we do not repeat statement Codeverb.com but only two or three lines of code we are printing here for 5 time Codeverb.com messages