Contents  1-5  6-11  12-16  17-21  22-27   28-33  34 - 38  39-46  Projects   MFC

   Contact
   Search
   C
   C++
   Visual Basic
   Java
   JavaScript
   DHTML
   Style Sheets
   About
   Active X
   TDC Binding
   PHP
   Perl and CGI
   Flash
   XML
   SQL
   Messages
   Chat
   MCSE
   Linux
   Cabling   
   ActionScript
   Downloads
   E-Cards   
 
    
    

Note: Updated!  See top of introduction page c1.html for using a C++ .Net compiler for these standard C++ tutorials.

Repetition structures are an integral part of any programming language, and C++ is no different.  Repetitive operations
are referred to as "iterations" in C++. 
Iterations involves doing the same thing again and again.  Iteration's principal
method is the loop, and these are enormously powerful structures in any programming language.   Many complex
problems can be solved by repeating simple steps over and over.  Loops are efficient, since by reducing larger problems into small, repetitive tasks, a small
amount of code can accomplish a great deal of input, processing and output (IPO).  The basic repetition structures in C++ are:
goto, while, while(true), do/while, and for.   In many instances, a block or two of source code is worth a thousand words.  So in this section, various repetition structures will be listed.  Copy and paste the code into your compiler.  Compile, link and execute each program until you
become familiar with how C++ repetition structures function.  Definitions and keywords will be highlighted and in bold.

"There are only two ways to live your life.  One is as though nothing is a miracle.
The other is as though everything is a miracle.
"  -  Albert Einstein

1. Goto - The "goto" structure can be employed in C++, but it is considered poor structure by many programmers and so rarely used.  Goto is
               used with a "label" in C++, which is simply a name of your choice (make sure it's not a keyword) followed by a semicolon.

#include <iostream.h>
int main()
{
    int counter = 0;      // initialize counter


    loop: counter ++;     // top of the loop
    cout << "counter: " << counter << "\n";
		
    if(counter < 5)            // test the value
       goto loop;              // jump to the top

    cout << "Complete. Counter: " << counter << ".\n";
    
    return 0;
}

2. While - Unlike do/while, a block of code in a while loop may never occur if the condition is not met.

#include <iostream.h>
int main()
{
    int counter = 0;          // initialize the condition

    while(counter < 5)         // test condition still true
    {
      counter++;              // body of the loop
      cout << "counter: " << counter << "\n";
    }
   
    cout << "Complete. Counter: " << counter << ".\n";
    
    return 0;
}

3. Break and Continue - The keyword "break" can be used to forcibly exit a loop before a condition is met.  You should avoid hard coding breaks
                                      into your loops unless absolutely necessary, as they can be error-prone and difficult to debug.  The keyword "continue"
                                      forces a loop back into iteration.

#include <iostream.h>
int main()
{
	unsigned short small;
	unsigned long  large;
	unsigned long  skip;
	unsigned long target;
	const unsigned short MAXSMALL=65535;
	cout << "Enter a small number: ";
	cin >> small;
	cout << "Enter a large number: ";
	cin >> large;
	cout << "Enter a skip number: ";
	cin >> skip;
	cout << "Enter a target number: ";
	cin >> target;
	cout << "\n";
	// set up 3 stop conditions for the loop
	while(small < large && large > 0 && small < MAXSMALL)
        {
		small++;
		if (small % skip == 0)  // skip the decrement?
		{
			cout << "skipping on " << small << endl;
			continue;
		}
		if (large == target)    // exact match for the target?
		{
			cout << "Target reached!";
			break;
		}
		large-=2;
	}                   // end of while loop
	cout << "\nSmall: " << small << " Large: " << large << endl;

	return 0;
}

4. While True - The while true loop will continue until a condition becomes false or a break is encountered.

#include <iostream.h>
int main()
{
	int counter = 0;
	while(true)
	{
		counter ++;
		if(counter > 10)
			break;
	}
	cout << "Counter: " << counter << "\n";

	return 0;
}

5. Do / While - Unlike a while loop, a do/while loop executes its code first, then it evaluates its test condition.  This guarantees that the block of
                       code in the do/while executes at least once, even if the test condition is not met.

#include <iostream.h>
int main()
{

	int counter;
	cout << "How many hellos? ";
	cin >> counter;

	do
	{
		cout << "Hello\n";
		counter--;
	}  
        while(counter > 0);

                cout << "Counter is: " << counter << endl;

	return 0;
}

6. For Loops - For loops are some of the most useful and flexible loops in C++.  They are comprised of three basic parts:
                      1 - initialization - A variable is initialized with a value to start the loop.
                      2 - test condition - A condition is tested for to end the loop.
                      3 - action - What to do each time the loop iterates (usually increment or decrement a variable). 

    The three parts are each separated by a semicolon.  Example:

#include <iostream.h>
int main()
{
	int counter;

	for(counter = 0; counter < 5; counter++)
	{   
            cout << "Looping! "; 
        }
	cout << "\nCounter: " << counter << ".\n";

	return 0;
}

For loop with multiple expressions:

//For loop with multiple expressions
#include <iostream.h>
int main()
{
	for(int i=0, j=0; i<3; i++, j++)
        {
	    cout << "i: " << i << " j: " << j << endl;
        }
	return 0;
}

For loop with null statement:

#include <iostream.h>
int main()
{
	int counter = 0;
	for( ; counter < 5; )
	{
		counter++;
		cout << "Looping!  ";
	}
	cout << "\nCounter: " << counter << ".\n";

	return 0;
}

For loop that’s empty – infinite loop without break:

//For loop that’s empty – infinite loop without break
#include <iostream.h>
int main()
{
	int counter=0;       // initialization
	int max;
	cout << "How many hellos?";
	cin >> max;

	for(;;)          // an infinite for loop that doesn't end
	{
		if(counter < max)       // test
		{
			cout << "Hello!\n";
			counter++;          // increment
		}
		else
			break;
	}

	return 0;
}

For loop with NULL:

#include <iostream.h>
int main()
{
	for(int i = 0; i<5; cout << "i: " << i++ << endl)
		
            {  ;  }

	return 0;
}

Nested For Loops:

//Nested For loops 
#include <iostream.h>
int main()
{
	int rows, columns;
	char theChar;

	cout << "How many rows? ";
	cin >> rows;
	cout << "How many columns? ";
	cin >> columns;
	cout << "What character? ";
	cin >> theChar;

	for(int i = 0; i<rows; i++)
	{
		for(int j = 0; j<columns; j++)
			cout << theChar;
		cout << "\n";
	}

	return 0;
}

Drawing Shapes with for loops:

#include <iostream.h>
//Function prototypes
void DrawRectangle();
void DrawTriangle1();
void DrawTriangle2();
int main()
{
    cout << endl << endl;
    DrawRectangle();
    DrawTriangle1();
    DrawTriangle2();
    
    cout << endl << endl << "End of the program!";
    cout << endl << endl;
    return 0;
}
//Function definitions
void DrawRectangle()  {
     for(int row = 1; row <= 5; ++row ) {
         for(int column = 1; column <= 15 ; ++column ) {
             cout << "*";
         } //ends 2nd for loop
         cout << endl;
     } //ends 1st for loop
         cout << endl << endl << endl;
} //end function

void DrawSquare() {
     for(int row = 1; row <= 15; ++row ) {
         for(int column = 1; column <= 15 ; ++column ) {
             cout << "*";
         } //ends 2nd for loop
         cout << endl;
     } //ends 1st for loop
            
         cout << endl << endl << endl;

}  //end function

void DrawTriangle1() {

     int i, j ;

     for(i = 1 ; i <= 5 ; i++ )
     {
         for(j = 1 ; j <= i ; j++)
         {
             cout << "*";
         } //ends 2nd for loop

         cout << "\n";
     } //ends 1st for loop
} //end function


void DrawTriangle2() {
     int i, j;
     cout << endl << endl;

     for(i = 1 ; i <= 5 ; i++ )
     {
         for(j = 1 ; j <= 5 ; j++)
         {
             if(i > 5 - j)
             {
                 cout << "*";
             }   
             else
             {
                 cout << " ";
             }
         } //ends 2nd for loop

         cout << endl;  
     } //ends 1st for loop

} //end function



void DrawDiagonalO() {

     int i, j ;

     for(i = 1 ; i <= 5 ; i++ )
     {
         for(j = 1 ; j <= 5 ; j++)
         {
             if(i == j)
             {   
                 cout << "O";
             }
             else
             {
                 cout << "*";
             }
         } //ends 2nd for loop

         cout << endl;
     } //ends 1st for loop
} //end function
Output:

***************
***************
***************
***************
***************
*
**
***
****
*****


    *
   **
  ***
 ****
*****
 

Recursion, nested For loops and iteration for Fibonacci numbers:

Calculating the Fibonacci series is a very popular example in programming tutorials.  It is a fun mathematical construction to play with, and it illustrates the effectiveness of looping, iteration and recursion to solve a more complex problem by reducing it into a set of smaller problems and solving them.  The Fibonacci series appears as a pattern where every number is the sum of the two preceding numbers that come before it.  This pattern appears throughout the observable universe as both microcosmic spiraling fractal patterns, such as those in DNA, bacteria, crystal structures, snail shells, leaves, and tree branches, and in macrocosmic spiral constructions such as galaxies and super clusters.  It is amazing how many patterns can be observed to conform to the Fibonacci series in nature, perhaps due to a balancing act of the four forces, and as a result it is sometimes referred to as the "golden mean".  Example:

1 1  2  3  5  8  13  21  are numbers in this series, as 1+2 = 3,  2+3 = 5,  3+5 = 8,  5+8 = 13,  and  8+13 = 21.

To calculate this series using recursion, we will create a function.  We will pass in a value to this function and attempt to calculate the fibonacci series for it.  If the number is less than 3, we will do nothing except return a 1, as 1 is the beginning number in the Fibonacci series.  If the number passed in is greater than 3, we will perform some recursive magic.  We will create a loop that initializes itself by taking whatever we pass in to it and subtracting 3 from it.  We will then iterate through this loop until what we pass in is no longer greater than 0.  Each time we iterate through this loop, we will decrement (subtract 1 from) the value we passed in.  To get each number in the Fibonacci series, we add the two before it together.  So if we pass a 5 to our function, this would occur:

Let's start with the lowest number in the series, 1, and add the next number, 2.  Let's repeat this until we reach 5: 
1+1 = 2
1+2 = 3
2+3 = 5

If we pass 8 into our function, we will need to repeat the process (n-3), or (8-3), or 5 times:

Let's start with the lowest number in the series, 1, and add the next number, 2.  Let's repeat this until we reach 21:
0+1 = 1
0+1 = 1
         
//Subtracting 1st 3 numbers in test condition.
1+1 = 2
         
//This leaves 5 numbers to reach position 8, which is 21.
1+2 = 3
2+3 = 5
3+5 = 8
5+8 = 13
8+13 = 21

#include <iostream.h>
//Function declaration and prototype
int fib(int position); 
int main()
{
	int answer, position;

	cout << "Which position? ";
	cin >> position;
	cout << "\n";
        //Call the Fibonacci function
	answer = fib(position);  
	cout << answer << " is the ";
	cout << position << "th Fibonacci number.\n";

	return 0;
} //end main()

//Function definition
int fib(int n)
{
      int minusTwo; 
      int minusOne; 
      int answer;
      minusTwo=1;
      minusOne=1;
      answer=2;
      if(n < 3)
	 return 1;  //ends function
      for(n = n-3; n > 0; n--)  //like saying for(n -= 3; n; n--)
      {
		minusTwo = minusOne;
		minusOne = answer;
		answer = minusOne + minusTwo;
      }
      return answer;
} //Close function

When we pass in a 5, we will subtract 3 to account for the first three numbers in the series, then iterate with what is left.  The first time through the loop, answer = 2 + 1, or 3.  The second time through, answer = 3 + 2, or 5.  Then we fall out of the loop.  2 loop iterations + the 3 numbers we bypassed make 5.  5 is the 5th Fibonacci number.    Example:  1  1  2  3  5  8 .

If we pass in 13, we subtract 3 to account for the first three numbers.  Then, the first time through the loop, answer = 2 + 1, or 3.  The second time, answer = 3 + 2, or 5.  The third time, answer = 5 + 3, or 8.  The fourth time, answer = 8 + 5, or 13.  We looped 4 times, and 4 + the three numbers we bypassed make 7.  Therefore, 13 is the 7th Fibonacci number.   Example:  1  1  2  3  5  8  13  21 .
 


©2004 C. Germany