CPP - Loops

From Global Programming Syntax

Jump to: navigation, search

Loops are one of the most basics in any language and are used for a wide range of purposes. The reason for having a loop is so that you do not need to re-do the same code over and over with endless if statements to check weather to continue. Alternatively the goto statement can be used just like a loop. In fact before c++ and many other modern languages, the goto statement was the only way to create a loop. So to make a loop below is an example of a for loop and a while loop both doing the same thing.

#include <iostream>
int main() {
for (int i=0;i<10;i++) {
std::cout << i;
}
 
std::cout << std::endl;
 
int i=0;
while (i<10) {
std::cout << i;
i++;
}
std::cout << std::endl;
system("PAUSE");
return 0;
}

Basically this code tells the computer to display numbers 0 to 9 on the first and second row then to pause. In this case the while and for loops are doing exactly the same thing. So to start off lets see how to while loop works. Above the while loop i=0. Then it goes into a loop until variable i is equal or greater than 10. After that the loop breaks and it goes past the loop. Below that it displays the number variable i stores. Then at the end of the while loop is the variable i being added +1.

Now to compare the while and the for loop. In the for loop you will notice that i=0 is inside the loop statement. That is because the loop statement is separated into 3 parts. The first part is what to do before the loop then the middle is the same as whats in the while loop statement and the last part of the statement is what to do at the end of each loop. So in this case we want to assign variable i the value 0 before the loop then for each loop round test if i<10. If that is not true then the loop will break/end. And the last part we want to add 1 to the variable i every loop round. Then inside the loop all we need to do is just display variable i and it's done.

Then you may ask "Why do we need a for loop when we have a while loop?". The answer is simple. For loops are faster when dealing with numbers but while loops are faster when dealing with true/false statements. So they both have their advantages when used properly.

Personal tools
languages
page stats
Toolbox