CPP for loop

Using for loop statement

for loop combines the three steps of initializing, testing, and incrementing into one statement:

Source code Result
// Looping with for

#include <iostream>

int main() {
  int count;
  // The initializing part is: count = 0
  // The testing part is     : count < 5
  // The incrementing part is: count++ 
  for (count = 0; count < 5; count++)
    std::cout << "I got a hotdog !\n";
  std::cout << "count: " << count << std::endl;
  return 0;
}
I got a hotdog !
I got a hotdog !
I got a hotdog !
I got a hotdog !
I got a hotdog !
count: 5

You can download this example here (needed tools can be found in the right menu on this page).

You can have Empty Loop both within the for Statement or within the while statement.

  • In these loops you have to use at least one break to end the loop and/or a continue statement to control the program flow.
  • The continue statement jumps to do a new test in any loop.
  • The break statement jumps out of any loop.
Example of a empty for loop:
Source code Result
// Demonstrates endles loop with break and continue
#include <iostream>

int main(){
  using namespace std;
  int count=0, max=5;
  for (;;) {            // A for loop that doesn't end
    if (count < max) {  // test
      count++;          // increment
      if (count==2) {
        continue;
      }
      // All counts are listed except number 2  
      cout << "Counter : " << count << endl;
    }
    else
      // Must have a break in a endles loop like this
      break;
  }
  return 0;
}
Counter : 1
Counter : 3
Counter : 4
Counter : 5

You can download this example here (needed tools can be found in the right menu on this page).

You can have NO Statement in a for Loop, but the use of it is rare:

Source code Result
//Demonstrates null statement
// as body of for loop
#include <iostream>
int main()
{
  for (int count = 0;
       count<5;
       std::cout << "count: " << count++ << std::endl)
// There is no statement in the body of the for loop
    ;
  return 0;
}
count: 0
count: 1
count: 2
count: 3
count: 4

You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.