Introduction to Programming and C++

Contents Previous Topic Next Topic

In a previous topic, we covered while loops. We will now look at a certain style of while loop which appears so often that it has been given its own name.

To begin, Program 1 calculates the factorial of an integer entered by the user by using a while loop.

Program 1. Calculating the factorial of an integer.

#include <iostream>

using namespace std;

int main() {
	int n;

	cout << "Enter a positive integer: ";

	cin >> n;

	int result = 1;
	int m = 1;

	while ( m <= n ) {
		result *= m;
		++m;
	}

	cout << n << "! = " << result << endl;

	return 0;
}

Three of the statements are highlighted. Let us examine each of these statements:

int m = 1
We declare m to be an integer and initialize it.
m <= n
We continue looping so long as this condition is satisfied (i.e., it evaluates to true).
++m
At the end of the while-loop, we modify the variable m (in this case, increasing it by 1).

This is so common in programming that it was decided to separate this out into a special type of loop. With a while loop, only the condition was specified within the parentheses. A for loop contains all three components:

  1. Initialization
  2. Condition, and
  3. Modification.

and to demonstrate, by example, consider Program 2 which is identical to Program 1 in functionality.

Program 2. Calculating the factorial of an integer using a for loop.

#include <iostream>

using namespace std;

int main() {
	int n;

	cout << "Enter a positive integer: ";

	cin >> n;

	int result = 1;

	for ( int m = 1; m <= n; ++m ) {
		result *= m;
	}

	cout << n << "! = " << result << endl;

	return 0;
}

Any good compiler will turn both of these into the same executable program, so why do we have the two forms? In the while loop, the information is spread across three lines. If the body of the while loop was larger, it may be frustrating to find the terminating increment statement. Also, by having the ++m at the bottom, another programmer editing this code might (accidentally) insert code below this statement, and thereby use the wrong value of m. The for loop nicely summarizes all the information in a single line:

We begin with m = 1, we continue looping until m <= n, and with each loop, we increment m.

Program 3 approximates ex by using a 21-term Taylor series.

Program 3. Approximating the exponential function.

#include <iostream>

using namespace std;

int main() {
	double x;

	cout << "Enter a real number: ";

	cin >> x;

	// Approximate exp(x) using a 21-term Taylor series:
	//
	//         1   2   1   3          1   20
	// 1 + x + -- x  + -- x  + ... + --- x
	//         2!      3!            20!

	double result = 1.0;
	double term = 1.0;

	for ( int n = 1; n <= 20; ++n ) {
		term *= x / static_cast<double>( n );
		result += term;
	}

	cout << "The approximation of exp(" << x << ") is " << result << endl;

	return 0;
}

The result is more compact, cleaner, and clearer.

Variations

A for loop does not always have to start at 1, and usually it starts at 0. The modification statement need not always increment the value of n. Each of the following Programs 4, 5, 6, and 7 perform a different type of loop. Before you run them, try to determine what will happen.

Program 4. For loop example 1.

#include <iostream>

using namespace std;

int main() {
	int n;

	cout << "Enter an integer: ";

	cin >> n;

	int result = 0;

	for ( int i = 0; i < n; i += 3 ) {
		result += i;
	}

	cout << "The result is " << result << endl;

	return 0;
}

Program 5. For loop example 2.

#include <iostream>

using namespace std;

int main() {
	int n;

	cout << "Enter an integer: ";

	cin >> n;

	int result = 1;

	for ( int i = n; i > 1; --i ) {
		result *= i;
	}

	cout << "The result is " << result << endl;

	return 0;
}

Program 6. For loop example 3.

#include <iostream>

using namespace std;

int main() {
	int n;

	cout << "Enter an integer: ";

	cin >> n;

	int result = 0;

	for ( int i = 1; i < n; i *= 2 ) {
		result += i;
	}

	cout << "The result is " << result << endl;

	return 0;
}

Program 7. For loop example 4.

#include <iostream>

using namespace std;

int main() {
	int n;

	cout << "Enter an integer: ";

	cin >> n;

	int result = 1;

	for ( int i = n; i > 1; i /= 2 ) {
		result *= i;
	}

	cout << "The result is " << result << endl;

	return 0;
}

Questions

1. For each of programs 3, 4, 5, and 6, determine what the result will be with an input of 5.

2. For each of programs 3, 4, 5, and 6, determine what the result will be with an input of 13.

3. Write a program which prompts the user for a positive integer n and then calculates the integer value 2n using a for loop. Print the result.

4. Write a program which prompts the user for an integer n and then calculates the double 2.0n using a for loop. Your code should work for both positive and negative numbers. Print the result.

Hint: Split the problem into three cases (using a selection statement) based on n < 0, n = 0, and n > 0. Then solve each problem separately, realizing that 2.0-n = 0.5n.

Comment: you should do this example. In ECE 250, you will find in many of the projects, there will be a number of cases which you must implement. Instead of trying to split the problem into many different cases and solving each separately, some students will try to solve all problems at once. Compare your result for solving Question 4 with this stripped-down solution. While this may be an acceptable solution, it is not necessarily as clear. (On the other hand, you may disagree.)


Contents Previous Topic Top Next Topic