The For Loop


If you wanted to output the numbers between 1 and 10, you could write a program such as the following:

 #include <iostream> using namespace std; int main(void) {  int num = 1;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  cout << num++;  return 0; } 

However, you could write the same program with far less code by using a for loop:

 #include <iostream> using namespace std; int main(void) {  for (int num = 1; num <= 10; num++)  cout << num << " ";  return 0; } 

The difference between the two programs becomes more pronounced if you change the specification from outputting the numbers between 1 and 10 to outputting the numbers between 1 and 100. I won t rewrite the first program because it would take up too many pages; suffice it to say, you would have to add 90 more cout statements. However, the same program using a for loop would be:

 #include <iostream> using namespace std; int main(void) {  for (int num = 1; num <= 100; num++)  cout << num << " ";  return 0; } 

Indeed, by using the for loop, the same code could output the numbers between 1 and 1000 or even 1 and 10000; you just would need to change the 100 in the code to 1000 or 10000.

The for loop is one of three types of loops ; the other two (while and do while) will be covered in the next chapter. A loop is a structure that repeats the execution of code until a condition becomes false. Each repetition is called an iteration.

In the example that printed out the numbers between 1 and 10, the output of the value of num was repeated as long as the condition ”the value of num being less than or equal to 10 ”remained true. There were ten iterations of this loop; that is, the current value of num was outputted ten times.

The Syntax of the For Loop

Let s discuss the syntax of the for loop. The for keyword is followed by parentheses that contain three expressions that will be discussed in a moment. This line of code is followed by one or more statements.

The three expressions contained in the parentheses following the for keyword are separated by semicolons; there is no semicolon after the third expression since no expression follows it.

The first expression usually is used to initialize the value of a variable, typically referred to as a counter, to provide that variable with a starting value. In this example, the integer variable num is initialized to the starting value of 0. This initialization is the first action performed by the loop, and is only performed once.

The second expression is the condition, which must be true for the code inside the loop to execute. In this example, the condition is whether the current value of num is less than or equal to 10.

The third expression usually is used to update the value of the counter. In this example, the integer variable num is incremented. This expression executes at the end of each iteration, and only executes if the condition was true at the beginning of the iteration.

Note  

Postfix incrementing was used in this example and generally is employed by convention. However, the result would be the same if prefix incrementing were used, as only one operator is involved in this expression.

Therefore, the order of execution in the first iteration of the loop is

  1. The integer variable num is initialized to 1.

  2. The current value of num, 1, is compared to 10.

  3. Since the comparison is true, the current value of num , 1, is outputted.

  4. The value of num is incremented, becoming 2.

The order of execution in the second iteration of the loop is

  1. The current value of num, 2, is compared to 10.

  2. Since the comparison is true, the current value of num, 2, is outputted.

  3. The value of num is incremented, becoming 3.

Note that the initialization that occurred during the first iteration of the loop did not occur during the second iteration of the loop. As discussed previously, initialization occurs only once, in the first iteration of the loop.

This order of execution in the second iteration of the loop repeats during the third and following executions of the loop, each time incrementing the value of num through the tenth iteration of the loop, which executes in the following order:

  1. The current value of num, 10, is compared to 10.

  2. Since the comparison is true (10 is less than or equal to 10), the current value of num, 10, is outputted.

  3. The value of num is incremented, becoming 11.

In the next iteration of the loop, the current value of num, 11, is compared to 10. Since the comparison is false (11 is not less than or equal to 10), the for loop ends. The code inside the for loop does not execute, the value of num is not incremented, and the code following the for loop executes. In this example, the code following the for loop is the return 0 statement, so the program ends.

Note  

The preceding examples used the increment operator. However, you also can use the decrement operator. Changing the parentheses following the keyword to (int num = 10; num >= 1; num--) would result in the numbers between 1 and 10 being outputted in reverse. Note that the relational operator is changed from >= to <=.

In the example of outputting the numbers between 1 and 10, only one statement belonged to the for loop. However, as with the if structure, if more than one statement belongs to the for loop, then the statements must be contained within curly braces.

 for (int num = 1; num <= 10; num++)  {  cout << num << " ";  cout << "Next loop ";  } 

Also, as with the if structure, the statement or statements following the for keyword and parentheses will not execute if the parentheses are followed by a semi- colon since that would be interpreted as an empty statement. Accordingly, in the following code fragment, the only number that would output is 11:

 for (int num = 1; num <= 10; num++);  cout << num << " "; 

The reason the output would be 11 is that the loop continues, and the empty statement executes, until the condition fails when num is 11. The cout statement is not part of the for loop, so it executes when the for loop completes, outputting 11, the value of num after the loop finishes.

The expressions do not need be inside the parentheses following the for loop. In the following program, num is initialized before the for loop, and is incremented inside the body of the loop.

 #include <iostream> using namespace std; int main(void) {  int num = 1;  for (; num <= 10;)  {  cout << num << " ";  num++;  }  return 0; } 

Even though initialization and incrementing are not done within the parentheses, two semicolons are nevertheless within the parentheses to separate where the three expressions would be. While an expression may be empty, the semicolon nevertheless is necessary.

Beware the Infinite Loop

In the preceding program, if the statement num++ was omitted, the loop would never stop:

 #include <iostream> using namespace std; int main(void) {  int num = 1;  for (; num <= 10;)  {  cout << num << " ";  }  return 0; } 

The reason is that the condition num < = 10 would never become false since num would start at 0 and its value would never change because the statement num++ was omitted.

This loop that never stops executing is called an infinite loop. Usually, it manifests itself by a character or characters appearing in rapid succession in your console window, with the application never ending.

You would not intend an infinite loop in your code, but mistakes do happen; I have made this mistake a lot more than once. If it happens to you, don t panic. You can use the CTRL-BREAK keyboard combination to end the program. Knowing you have encountered an infinite loop, you then can correct the code error that caused it.

A Factorial Example

So far, use of the for loop has been relatively trivial, counting numbers in ascending or descending order. However, the for loop can be used for more sophisticated programs.

The following program calculates the factorial of a number inputted by the user . A factorial is the product of all the positive integers from 1 to that number. For example, the factorial of 3 is 3 * 2 * 1, which is 6, while the factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120.

 #include <iostream> using namespace std; int main(void) {  int num, counter, total = 1;  cout << "Enter a number: ";  cin >> num;  cout << "The factorial of " << num << " is ";  for (int counter = 1; counter <= num; counter++)  total *= counter;  cout << total;  return 0; } 

Input and output could be

 Enter a number: 4 The factorial of 4 is 24 

Breaking Out of a Loop

We previously used the break keyword in a switch statement. You also can use the break keyword in a for loop. The break keyword is used within the code of a for loop, commonly within an if / else structure. If the break keyword is reached, the for loop terminates, even though the condition still is true.

For example, in the following program, the user is given three tries to guess a number (which happens to be 3) between 1 and 10. However, if the user guesses the number on their first or second try, it would be pointless to ask them again to guess the number. Accordingly, if the user guesses the number, the break statement is used to break out of the loop.

 #include <iostream> using namespace std; int main(void) {  int num, counter, secret = 3;  cout << "Guess a number between 1 and 10\n";  cout << "You have 3 tries\n";  for (int counter = 1; counter <= 3; counter++)  {  cout << "Enter the number now: ";  cin >> num;  if (num == secret)  {  cout << "You guessed the secret number!";  break;  }  }  cout << "Program over";  return 0; } 

Here are two sample inputs and outputs. In the first one, the user tried three times without guessing correctly. In the second one, the user guessed correctly on their second try, so there was no third iteration of the loop due to the break keyword.

 Guess a number between 1 and 10 You have 3 tries Enter the number now: 2 Enter the number now: 4 Enter the number now: 6 Program over  ------------------- Guess a number between 1 and 10 You have 3 tries Enter the number now: 2 Enter the number now: 3 You guessed the secret number! Program over 

While the break keyword is part of the C++ language, I recommend you use it sparingly. Normally, the for loop has one exit point, the condition when it becomes false. However, when you use one or more break statements, the for loop has multiple exit points. This makes your code more difficult to understand, and can result in logic errors.

In the following program, the logical && (And) operator is an alternative to using the break keyword.

 #include <iostream> using namespace std; int main(void) {  int num, counter, secret = 3;  cout << "Guess a number between 1 and 10\n";  cout << "You have 3 tries\n";  bool keepgoing = true;  for (int counter = 1; counter <= 3 && keepgoing == true;  counter++)  {  cout << "Enter the number now: ";  cin >> num;  if (num == secret)  {  cout << "You guessed the secret number!";  keepgoing = false;  }  }  cout << "Program over";  return 0; } 

Before leaving the discussion of the break keyword, one additional use of it (in conjunction with the parentheses following the for keyword being empty of all three expressions) deserves mention simply because you may encounter it. The following program is a variant of the one that outputs numbers between 1 and 10 with the first and third expressions inside the parentheses being empty because num is initialized before the for loop and incremented inside the body of the loop. In this program, the second expression ”the condition ”is missing as well. Instead, the break keyword inside the if/else structure substitutes for that condition.

 #include <iostream> using namespace std; int main(void) {  int num = 1;  for (;;)  {  if (num > 10)  break;  else  {  cout << num << " ";  num++;  }  }  return 0; } 

Without the break keyword, the for loop would be infinite due to the lack of a second expression. Again, however, I do recommend against this use of the break keyword, and point it out simply because other programmers believe differently ”thus, you re likely to encounter it at some point in time.

The Continue Keyword

You also can use the continue keyword in a for loop. The continue keyword, like the break keyword, is used within the code of a for loop, commonly within an if/else structure. If the continue statement is reached, the current iteration of the loop ends, and the next iteration of the loop begins.

For example, in the following program, the user is charged $3 an item, but not charged for a baker s dozen . In other words, every 13 th item is free ”in other words, the user is charged for only a dozen items, instead of 13.

 #include <iostream> using namespace std; int main(void) {  int num, counter, total = 0;  cout << "How many items do you want to buy: ";  cin >> num;  for (int counter = 1; counter <= num; counter++)  {  if (counter % 13 == 0)  continue;  total += 3;  }  cout << "Total for " << num << " items is $" << total;  return 0; } 

Here are three sample inputs and outputs, illustrating that the price for 12 or 13 items is the same, but on the 14 th item the user again is charged an additional $3. The reason why the code charges the user no additional price for the 13 th item is that the continue statement is reached, preventing three dollars from being added to the total.

 How many items do you want to buy: 12 Total for 12 items is  -------------- How many items do you want to buy: 13 Total for 13 items is   ----------------- How many items do you want to buy: 14 Total for 14 items is 

While the continue keyword is part of the C++ language, I recommend, as I do with the break keyword, that you use it sparingly. Normally, each iteration of a for loop has one end point. However, when you use a continue statement, each iteration has multiple end points. This makes your code more difficult to understand, and can result in logic errors.

In the following program, the logical ! (Not) operator is an alternative to using the continue keyword.

 #include <iostream> using namespace std; int main(void) {  int num, counter, total = 0;  cout << "How many items do you want to buy: ";  cin >> num;  bool keepgoing = true;  for (int counter = 1; counter <= num; counter++)  {  if (! (counter % 13 == 0))  total += 3;  }  cout << "Total for " << num << " items is $" << total;  return 0; } 
Note  

You also could use the relational != (not equal) operator, changing the if statement to if (counter % 13 != 0) .

Nesting For Loops

You can nest a for loop just as you can nest if statements. For example, the following program prints five rows of ten X characters:

 #include <iostream> using namespace std; int main(void) {  for (int x = 1; x <= 5; x++)  {  for (int y = 1; y <= 10; y++)  cout << "X";  cout << '\n';  }  return 0; } 

The for loop for (int x = 1; x < = 5; x++) is the outer for loop. The for loop for ( int y = 1; y < = 10; y++ ) is the inner for loop.

With nested for loops, for each iteration of the outer for loop, the inner for loop goes through all its iterations. By analogy, in a clock, minutes are the outer loop, seconds the inner loop. In an hour , there are 60 iterations of minutes, but for each iteration of a minute, there are 60 iterations of seconds.

In the rows and columns example, for the first iteration of the outer for loop, the inner for loop goes through all ten of its iterations, printing ten X characters and one new line character. Then, for the next iteration of the outer for loop, the inner for loop again goes through all ten of its iterations, again printing ten X characters and one new line character. The same thing happens on the third, fourth, and fifth iterations of the outer for loop, resulting in five rows of ten X characters.

While nested for loops can be used to print rows and columns for tables, they also have other uses. For example, the following program prompts the user for the total number of salespersons as well as the number of sales per salespersons, and has the user input each sale of each salesperson, and then afterward displays the average sale for each salesperson. The number of iterations of the outer for loop will be the number of salespersons. The number of iterations of the inner for loop will be the number of sales per salesperson.

 #include <iostream> using namespace std; int main(void) {  int persons, int numSales;  cout << "Enter number of salespersons: ";  cin >> persons;  cout << "Enter number of sales per salesperson: ";  cin >> numSales;  for (int x = 1; x <= persons; x++)  {  int sale, total = 0;  float average;  for (int y = 1; y <= numSales; y++)  {  cout << "Enter sale " << y << " for salesperson "  << x <<": ";  cin >> sale;  total += sale;  }  average = (float) total / numSales;  cout << "Average sales for salesperson #" << x  << " is " << average << endl;  }  return 0; } 

The input and output could be

 Enter number of salespersons: 2 Enter number of sales per salesperson: 3 Enter sale 1 for salesperson 1: 4 Enter sale 2 for salesperson 1: 5 Enter sale 3 for salesperson 1: 7 Average sales for salesperson #1 is 5.33333 Enter sale 1 for salesperson 2: 8 Enter sale 2 for salesperson 2: 3 Enter sale 3 for salesperson 2: 4 Average sales for salesperson #2 is 5 
Note  

If you place a break or continue keyword in the inner loop, it will affect only that inner loop, and have no effect on the outer loop.




C++ Demystified(c) A Self-Teaching Guide
C++ Demystified(c) A Self-Teaching Guide
ISBN: 72253703
EAN: N/A
Year: 2006
Pages: 148

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