Problem 1 Solution: Maximum Number With A For-Loop

A for-loop is useful when the number of iterations (repetitions) is known before the loop begins. The function must "remember" the largest number seen at any point in the data entry. The variable max stores the largest number entered, and the program updates it whenever the user enters a larger number. The challenge is determining how to initialize max. The two functions solve the problem in different ways.

Function 1

int max1()
{
	int	max;

	cout << "Please enter a number: ";
	cin >> max;			// read first int

	for (int i = 0; i < 9; i++)	// read 9 ints in the loop
	{
		int	number;

		cout << "Please enter a number: ";
		cin >> number;

		if (number > max)
			max = number;
	}

	return max;
}
max1 version 1: for-loop finding the largest entered number - first entered number version. This version requires two pairs of prompt and read operations. The program saves the first entered value as the current maximum with the first pair, then iterates (loops) 9 times to complete the data entry with the second pair.

Function 2

#include <iostream>
#include <climits>
using namespace std;
	.
	.
	.
int max1()
{
	int	max = INT_MIN;

	for (int i = 0; i < 10; i++)
	{
		int	number;

		cout << "Please enter a number: ";
		cin >> number;

		if (number > max)
			max = number;
	}

	return max;
}
max1 version 2: for-loop finding the largest entered number - smallest representable integer solution. This version initializes max with the smallest integer that the system can store (highlighted). The system header file <climits> defines the symbolic constant INT_MIN and the program must #include it. The advantage of this version is that it requires only one prompt and one read statement.