Introduction to Programming and C++

Contents Previous Topic Next Topic

A selection (if) statement will execute either the clause exactly once. Most useful operations require that an operation be performed numerous times. A while loop is similar to a if statement, however, the body of the loop is repeatedly executed until the condition evaluates to false.

Program 1 prompts the user to enter an integer and the while loop continues looping until the user enters a negative number. If the user enters a negative number, the test n >= 0 will fail (it will evaluate to false) and will therefore continue executing at the // end of the loop.

Program 1. Prompting the user for an integer until the user enters 0.

#include <iostream>

using namespace std;

int main() {
	int n = 0;

	while ( n >= 0 ) {
		cout << "Enter a negative number to quit: " << endl;
		cin >> n;
	}

	// end of loop

	cout << "You entered a negative number.  Bye." << endl;

	return 0;
}

If we replaced the keyword while with if, the program would still execute, however, the body of the if statement would run at most once.

We will now look at a more fun example which uses a mathematical observation.

The Collatz Conjecture

Given an integer n, we will calculate a new integer based on the following rules:

  • If n is even, we will divide n by 2, otherwise,
  • n must be odd, so we calculate 3n + 1.

Thus, given an integer like 3, if we keep applying this rule, we get:

3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, 4, 2, 1, ...

It has been proposed that no matter what integer you start with, it must ultimately end up in the repetitive sequence 4, 2, 1, 4, 2, 1, ... .

Program 2 prompts the user for an integer and then continues making this calculation until we get a value of 1. It introduces a new operator % which returns the remainder of an integer division. For example, calculating 8 % 3 returns 2.

Program 2. Continue looping until the value n is 1.

#include <iostream>

using namespace std;

int main() {
	int n = 0;

	cout << "Enter a positive number: ";
	cin >> n;

	cout << n;

	while ( n != 1 ) {
		if ( n % 2 == 0 ) {  // if the remainder of n/2 is 0,
		                     // that is, if n is even
			n = n/2;
		} else {
			n = 3*n + 1;
		}

		// print a space followed by the new number
		cout << " " << n;
	}

	// print an end-of-line character
	cout << endl;

	return 0;
}

One formula the ancient Greeks were aware of was that if, given any real number x, if you calculate

x/2 + 1/x,

you get a better approximation of √2. Program 3 starts with the value of 2.0 as an the approximation to √2 and continues iterating until no change occurs.

Program 3. Approximating √2.

#include <iostream>

using namespace std;

int main() {
	double sqrt2 = 2.0;

	// continue looping while the next approximation
	// is different from the current approximation

	while ( sqrt2 != ( sqrt2/2 + 1/sqrt2 ) ) {
		sqrt2 = sqrt2/2 + 1/sqrt2;
	}

	cout << "The square root of two is approximately " << sqrt2 << endl;

	return 0;
}

Another example, which will lead to the next topic, is that of calculating the factorial of an integer. Program 4 calculates the factorial of an integer.

Program 4. 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 = result * m;
		m = m + 1;
	}

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

	return 0;
}

Suppse that the user entered a value of 4. The variable m is initialized to 1 thus we loop:

  • With the first loop, m = 1 and 1 <= 4 is true, so we enter the body, multiply result by 1 and add one to m.
  • With the second loop, m = 2 and 2 <= 4 is true, so we enter the body, multiply result by 2 and add one to m.
  • With the third loop, m = 3 and 3 <= 4 is true, so we enter the body, multiply result by 3 and add one to m.
  • With the fourth loop, m = 4 and 4 <= 4 is true, so we enter the body, multiply result by 4 and add one to m.
  • With the fifth loop, m = 5 but 5 <= 4 is false, so we continue executing at the end of the body of the loop by printing the result.

If you try this with a number like 15, you get the correct value of 15!. If you try this with a number like 32, you end up with an incorrect answer. In reality,

32! = 263130836933693530167218012160000000

however, this is too large for an int which can store numbers between -231 to 231 − 1. What happens here is wrapping: if the result of multiplying two integers is greater than 231 − 1, all bits higher the 32nd bit are ignored and the result is treated interpreted as a 32 bit integer.

A similar example is calculating a Taylor approximation of the exponential function. Program 5 calculates the first 21 terms of the Taylor approximation.

Program 5. 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;
	int n = 1;

	while ( n <= 20 ) {
		term = term * x / static_cast<double>( n );

		result = result + term;
		n = n + 1;
	}

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

	return 0;
}

Questions

1. Create the game of hi-lo. Store an integer and continue prompting the user to enter a guess. If the guess equals the integer stored, print "You're right." and stop looping, if the guess is greater than the stored number, print "High...", otherwise, print "Low...".

2. Write a program which converts a decimal integer into a hexadecimal integer by following the loop:

  1. Initialize n with the integer,
  2. While n != 0, perform the following:
    1. Find the remainder when dividing by 16 (n % 16),
    2. For a remainder of 0, 1, 2, ..., 8, 9, 10, 11, 12, 13, 14, and 15, print the character '0', '1', '2', ..., '8', '9', 'A', 'B', 'C', 'D', 'E', and 'F', respectively.
    3. Set n to be itself dividied by 16.
  3. Print an end-of-line character.

Note, this prints the hexadecimal number in reverse order: it prints the least-significant hexadecimal digit first. For example, 523 should be printed as B02 which represents the hexadecimal number 20B16.

References


Contents Previous Topic Top Next Topic