For Loops in C++

Introduction

This lab will provide students with an introduction to the fundamentals of conditional repetition in the C++ programming language. The focus of this lab is on how to solve complex problems using the C++ “for” statement. At the end of this lab, students will…

  • Be able to solve simple problems using C++ “for” statement
  • Understand the structure of C++ “for” statement

These exercises have two different types of answers. Some questions ask for answers to specific questions; you should collect these answers in a Microsoft Word document. Other exercises ask you to write code. Let’s begin!

Part 1: Counter-Driven Repetition in C++

The idea of repetition, repeating a set of statements until a condition becomes false, has many applications in computer programming. As a result, C++ provides us with several constructs we can use to do repetitive programming. We have see one such construct in (the while statement) and we will now focus on the for construct. The for construct allows us to do something called counter-driven repetition in a more compact manner.

While loops provide for conditional repetition within a program, allowing you to specify a statement or sequence of statements that you want executed as long as some condition holds. Since a while loop is controlled by a condition, it is usually the case that the number of repetitions cannot be predicted ahead of time. In contrast, there are many problems involving repetition where the number of repetitions is known ahead of time. In these cases, some action must be carried out a certain number of times in order to complete a task.

For example, suppose you wanted to sum the numbers from one to ten. You could do this by using a counter variable. A counter is a variable that keeps track of the number of occurrences of some event. A common use of counters is to keep track of the number of times a loop has executed, and so control the number of repetitions. For example, in the code below, we use a counter to ensure we only add the numbers from one to ten, inclusive.

     int count = 1, sum = 0;
                 
     while (count <= 10)
     {
        sum = sum + count;
        count = count + 1;
     }

The variable count is initialized to 1, signifying that no summation has been made yet. During each pass through the loop, the current value of the count variable is added to the value of sum. Afterwards, the value of count is incremented accordingly. When the count finally reaches 11, the loop test will fail and the loop will terminate.

For Loops

The above code is an example of a counter-driven loop, one whose number of repetitions is controlled by a counter. Counter driven loops always involve three components:

  1. Initialization of the counter variable to a starting value.
  2. Testing the counter variable for a terminating condition.
  3. Modifying the value of the counter variable to ensure an eventual end to the loop.

Since counter-driven loops of this form are common, C++ provides a variant of while loops that captures this pattern more succinctly. The general form of a for loop is:

 for ( /*initialize counter*/ ; /*test counter*/ ; /*modify counter*/) 
 {
     // statements to execute....
 }

As this general form shows, a for loop combines all of the components of a counter-driven loop, making the loop more compact and easier to read. In particular, the steps involving the loop counter: initialization, testing, and modification, are all isolated on one line, separated by semi-colons. Since these statements control the behavior of the loop, listing them together makes it easier to grasp the overall behavior of the loop. Separating the loop control statements from the actual code to be executed in the body of the loop also makes it easier to focus on the actions performed by the loop.

In all other respects, a for loop behaves precisely the same as its while loop counterpart. In particular, the initialization of the loop counter (the first component of the for loop header) is executed first. Then, the loop test (the second component) is evaluated, and if the test succeeds then the body of the loop is executed. After the loop body is executed, the loop counter is incremented (the third component) and the loop test is reevaluated, possibly re-executing the loop body as before. As an example, the code below that uses a for loop to sum the numbers from one to ten:

int sum = 0;
                 
for (int count = 1; count <= 10; count = count + 1)
{
   sum = sum + count;
}

Notice in the above example the use of int count = 1 as the initialization component. When we want to only use a variable within a for loop, we can create the variable in this manner. The variable is created when the loop begins and is destroyed when the loop ends; i.e. the variable count would not be accessible in code following the loop.

Watch and listen to the For Loops in C++ podcast below:
for

Part 2: Applications of For Loops

We previously examined the the while statement as a general-purpose loop structure. These loops can be used for any type of conditional repetition needed by our programs. However, alternative repetition constructs are available for specific purposes. Recall that the purpose of the for construct is to allow us to perform counter-driven repetition in a more compact manner.

In the While Loops in C++ lab, the program CompoundInterest was one of the examples used to illustrate the use of a while statement. This program involves the use of counter-driven repetition. If we swap out the while statement for a for statement, the code in main would look like the following:

int main()
{
   double interest_rate = 0.0;   // stores the interest rate
   double balance = 0.0;         // stores the user balance

   // prompt the user and... 
   cout << "Enter a starting balance and interest rate, "
        << "separated by a space: ";   
   //  ...input two values...
   cin  >> balance >> interest_rate;

   // set up the output for two digits of precision...
   cout.setf(ios::fixed);    // show decimal
   cout.precision(2);        // two digits on the right

   for (int year = 1; year <= 10; year++)
   {
       // compute the new balance for this year...
       balance = balance + (balance * interest_rate);

       // show the balance each year...
       cout << setw(4) << year << setw(15) << balance << endl;     
   }
   
   // return "success" to the operating system... 	 
   return 0;
}

Ultimately the code in this version is more compact. Since we have separated the loop control statements from the actual code to be executed in the loop body, the purpose of the loop can be made more apparent to the casual reader: to compute a new balance and to output that new value.

For Loops and Grade Calculators

Suppose we wanted to write a C++ program to compute student grades. Our program would take one input at the beginning:

  • A Student ID, a string of exactly four characters

Next, our program would input exactly 11 of the following values:

  • An Exam Score, an int in the range [0-100]

Once the input was finished, our program would calculate the total score by throwing out the lowest score and computing the students’ grade as a percentage. One possible dialog between the program and the user would look like the following:

Enter the student ID: 11AB

Enter Exam Score #0:  80
Enter Exam Score #1:  82
Enter Exam Score #2:  87
Enter Exam Score #3:  74
Enter Exam Score #4:  68
Enter Exam Score #5:  89
Enter Exam Score #6:  80
Enter Exam Score #7:  92
Enter Exam Score #8:  83
Enter Exam Score #9:  81
Enter Exam Score #10: 84

The lowest score was removed (68).
Student 11AB has a total score of 832 (83.20 percent, B).

This problem is well-suited to the use of for loops. The problem involves a repeated set of instructions (the instructions to provide input) which differ only in terms of the prompt: each user prompt includes a number (#0, #1, etc) which increases by 1 each time. The repeated prompting of the user has a defined starting point (Exam Score #0) and a defined ending point (Exam Score #10). The succession of prompts is an example of counter-driven repetition.

Exercise 1: Create a new C++ code file called GradeCalculator.cpp and construct the program described above. A few notes as you construct the program:

  • The percentage score must be output with two digits of precision. Letter grades should follow the following scale: [0…60.00)% = F, [60.00-70.00)% = D, [70.00-83.00)% = C, [83.00-93.00)% = B, and [93.00-100.00]% = A. Be sure to validate all input.
  • Repetition and conditional constructs must be used where appropriate.

Compile and Build your program to verify it works as expected. Enter in several different tests cases to verify your program’s logic.

Part 3: The Game of Roulette

The idea of Monte Carlo Methods involves processes whereby we can predict the behavior (on average) of a random event. The end result of the application of this methodology is a numerical probability (likelihood) that a given event will occur. For example, suppose we have an American roulette wheel. This version of a roulette wheel has 38 numbers on it (1-36, 0, and 00). The “slots” for each number are each colored according to the following chart:

Even or odd numbers… …IN RANGE …HAS COLOR
Odd 1-9 Red
Odd 19-27 Red
Even 12-18 Red
Even 30-36 Red
N/A 0 or 00 Green

All slots falling outside of these values are colored Black.

Exercise 2: Create a C++ program which simulates “spins” of the roulette wheel. Allow the user to specify how many spins to perform, and print out a summary of how many times the colors Red, Green, and Black are “winners”, i.e. the spin lands on these colors. Perform some tests of your own and watch the results. Your output should consist of three things:

  • The total number of spins;
  • The number of times each of Red, Green, and Black “win”;
  • The winning percentage for each color.

To simulate a die roll you can use the spin() function, as shown below. Note that we are using the value 37 to represent 00. You will need to write this function into your code:

/////////////////////////////////////////////////////////////////////////////
//
//   FUNCTION NAME: spin
//      PARAMETERS: None
//     RETURN TYPE: int
//         PURPOSE: Returns a random integer in the range 0-37.
//
////////////////////////////////////////////////////////////////////////////

int spin()
{
    static bool initialized = false;    // initialize the static variable

    if (!initialized)
    {
       // Set the seed value for generating random numbers. 
       srand((unsigned)time(0));

       // set the flag
       initialized = true;
    }

    // This computes a random integer between 0 and 37 using the
    // Standard C++ rand() function.

    // Get the random number.
    int rand_num = rand();

    // Convert the number to a number in the range [0…37]...
    rand_num = (rand_num % 38);

    // return the generated number...
    return rand_num;
}

Part 4: Vocabulary Words

You will be assessed on your knowledge of the following terms and concepts as well as the C++ concepts discussed in this document. As a result, you are encouraged to review these terms in the preceding document.

Boolean – true or false.

Conditions/Conditional Expressions – expressions which evaluate to one of two possible values: true or false.

Conditional Repetition – the repeated execution of a statement or a sequence of statements.

Counter-Driven Repetition (Loop) – a loop whose number of repetitions is controlled by a counter. These loops always involve three components: initialization of the counter variable to a starting value; testing the counter variable for a terminating condition; and modifying the value of the counter variable to ensure an eventual end to the loop.

Counter Variable – A variable (usually an integer) which keeps track of the number of loop iterations.

Infinite Loop – Occurs when a conditional expression never becomes false, causing a loop to repeat forever. It appears to the user as a non-responsive or “hanging” program.

Iterations – the “cycles” of a loop; in other words, the number of times the loop body is repeated.

Loop –In C++, a construct that repeats a series of statements.

Loop Body – the portion of a loop inside { } .