7.7 Loops and Repetition

7.7 Loops and Repetition

C++ comes equipped with a number of programming constructs called loops. These can be used to execute the same block of code for a specified number of times, or continuously until a specific condition is met. A mundane example might be a scenario where the phrase "hello world\n" is to be printed to the screen 10 times, line after line. Using what we've learned so far, the programmer would need to write a "std::cout <<" statement 10 times, once for each time the line is to be printed. Using loops, it's possible to write that statement once and have the program repeat it 10 times. Of course, loops are typically used for more elaborate tasks than simply repeating text. As we shall see, loops are fundamental to programming and are useful for all sorts of tasks. Loops come in various forms, which are explored in the following subsections.

7.7.1 For Loop

The For loop is used to repeat a block of code for a specified number of times. Once the loop is completed, program execution resumes as normal at the end of the loop. The For loop is represented by the for keyword. It also has a start value, end value, and increment value. It has the following form:

      for(start, end, increment)      {          do something;      } 

7.7.2 Using For Loops

For loops can be used to repeat code a specified number of times. As shown in the previous section, For loops work using the principle of a counter, usually an integer variable. Each cycle of the loop is called an iteration, and the counter is used to keep track of the number of passed iterations. When the loop begins, the counter is initialized to a starting value (say 0), and as each iteration passes, the counter increases (increments). The For loop is also given an end target for the counter; this is the value the counter must reach for the loop to end. Consider the following code:

      #include <iostream>      int main()      {         int Number = 0;         std::cout<<"How many times to print?\n";         std::cin >> Number;         for(int Counter = 0; Counter < Number; Counter++)         {            std::cout<<"This is the "<<Counter<<" Iteration of the loop\n";         }         return 0;      } 


Counter is the name of the integer variable that keeps track of the iteration count. The loop begins at 0 (Counter = 0) and continues as long as Counter is less than Number (Counter < Number). So, if Number = 10, then Counter will range from 0 to 9. On each increment, Counter increases by 1 (Counter++). ++ is the increment operator, and is used to increase a value by 1. So, Counter++ = Counter + 1.

7.7.3 While Loop

Unlike the For loop, the While loop is called a pre-test conditional loop. It's called a "conditional loop" because rather than execute a specified number of times like the For loop, the While loop executes repeatedly, without end, until some condition is met to bring about its end. It's called "pre-test" because it checks to see whether it should proceed at the beginning of an iteration, not at the end. An example of the While loop would be as follows: A screen appears asking whether a user would like to quit an application; the user is expected to press either Y for Yes or N for No. The application will wait for an answer and respond according to whether Y or N is pressed, but if another key besides N or Y is pressed, then the user response will be ignored and the question will be asked again. This is set on a loop that is designed to repeatedly ask the same question until a valid response is entered. The While loop has the following form:

      while(condition)      {          do something;      } 

7.7.4 Using the While Loop

As mentioned, the While loop repeats a block of code until explicitly told to stop, that is, when some condition is met. If the condition is never met-either because something doesn't happen or because of an oversight on the programmer's part-then the While loop will loop forever, which is called an infinite loop. Causing this is bad programming practice, and the user will need to manually terminate a program that enters an infinite loop. Consider the following sample code:

      #include <iostream>      int main()      {         char key;         while((key != 'Y') && (key != 'N'))         {              std::cout<<"Exit? Press Y or N\n";              std::cin >> key;         }         return 0;      } 

Notice the While condition contains the logical operator AND (&&) to combine two conditional statements. Here, this program loops as long as Y or N isn't pressed.

7.7.5 Do-While Loop

C++ has one final form of loop called Do-While, which, like a While loop, is a conditional loop. However, a Do-While loop is post-test instead of pre-test. This means the loop condition is checked at the end of the iteration instead of at the beginning. The difference between pre-test and post-test might not be immediately apparent. In short, pre-test loops like While might not execute at all because their condition is checked at the beginning of an iteration. So, if the condition is true from the beginning, then the condition is already met and the While loop is not executed. Post-test loops like Do-While, however, will always execute at least once because the condition is not checked until the end of each iteration. Do-While takes the following form:

      do      {          do something;      }      while(condition) 

7.7.6 Using the Do-While Loop

Do-While is a post-test loop and will execute a block of code until a specified condition is met. Consider the following code. Note that many of the concepts presented in this chapter are used in the following code sample.

      #include <iostream>      int main()      {         int Numbers[] = {5, 7, 8, 9, 10};         int Total = 0;         int Loop_Pos = 0;         do         {            std::cout<<"Adding "<<Numbers[Loop_Pos]<<"\n";            Total = Total + Numbers[Loop_Pos];            Loop_Pos++;         }         while(Total < 10);         std::cout<<"Total: "<<Total<<"\n";         return 0;      } 

Worth mentioning in this sample is how the array index is the counter of a loop: Numbers[Loop_Pos].

Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

Similar book on Amazon
Beginning C++ Through Game Programming
Beginning C++ Through Game Programming
Beginning Game Programming
Beginning Game Programming
The Ultimate Guide to Video Game Writing and Design
The Ultimate Guide to Video Game Writing and Design

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net