Loops

FOR LOOP:

The syntax for a for loop is 

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

Example:


#include <iostream>

using namespace std; // So the program can see cout and endl

int main()
{
  // The loop goes while x < 10, and x increases by one every loop
  for ( int x = 0; x < 10; x++ ) {
    // Keep in mind that the loop condition checks 
    //  the conditional statement before it loops again.
    //  consequently, when x equals 10 the loop breaks.
    // x is updated before the condition is checked.    
    cout<< x <<endl;
  }
  cin.get();
}


WHILE loop:

while ( condition ) { Code to execute while the condition is true } The true represents a boolean expression which could be x == 1 or while ( x != 7 ) (x does not equal 7). It can be any combination of boolean statements that are legal. Even, (while x ==5 || v == 7) which says execute the code while x equals five or while v equals 7. Notice that a while loop is the same as a for loop without the initialization and update sections. However, an empty condition is not legal for a while loop as it is with a for loop. 

Example:


#include <iostream>

using namespace std; // So we can see cout and endl

int main()
{ 
  int x = 0;  // Don't forget to declare variables
  
  while ( x < 10 ) { // While x is less than 10 
    cout<< x <<endl;
    x++;             // Update x so the condition can be met eventually
  }
  cin.get();
}

DO..WHILE

The structure is


do {
} while ( condition );

Example:


#include <iostream>

using namespace std;

int main()
{
  int x;

  x = 0;
  do {
    // "Hello, world!" is printed at least one time
    //  even though the condition is false
    cout<<"Hello, world!\n";
  } while ( x != 0 );
  cin.get();
}











No comments:

Post a Comment