Loops in C++

Loops are probably one of the most important programming concepts in existence. There are so many applications of loops it would be impossible to list them all. To name a few though, things like parsing an array, trapping for errors, and animation. Also, since it will allow you to execute a block of code over and over, it saves time and typing. Now, depending on what kind of programming language you came from, loops might already be familiar to you, but if you’ve come from a low level programming language such as assembly or GWBasic, you are probably more familiar with jump or goto statements. Well, loops take into account all that lovely comparison crap you used to have to do before and puts it into one nice package.

C++ for Loop

The easiest and most used of these loops is the for loop.

for Loop Syntax

for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}

for Loop Example

#include <iostream>
using namespace std;

int main() {

for ( int x = 0; x < 10; x++ ) {

cout<< x << “\n”;

}
return 0;

}

C++ while Loop

The while loop is almost exactly the same as the do loop except that its condition is tested at the start of the loop instead of at the end… and the format is slightly different. The easiest way to see this is simply to re-write the above example with a while loop.

while Loop Example

#include <iostream>

using namespace std;
int main()
{

int x = 0;

while ( x < 10 ) {

cout<< x << “\n”;
x++;

}

return 0;

}

C++ do.. while Loop

The do while loop is like the while loop except that the condition is tested at the bottom of the loop.

do.. while Loop Syntax

do {

statement(s);

} while (condition);

do.. while Loop Example

#include <iostream>

using namespace std;

int main()
{

int x;

x = 0;
do {

cout<<“Hello, world!\n”;

} while ( x != 0 );

return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *