Problem 2 Solution: Maximum Number With A While Loop

The program reads integers from the console until the user enters a -1. It identifies and returns the largest number entered. All integers ≥ 0 are valid.

int max2()
{
	int	max = -1;
	int	number;

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

	while (number >= 0)
	{
		if (number > max)
			max = number;

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

	return max;
}
max2: while-loop finding the largest entered number. This solution requires the program to initialize max (the largest number entered so far) before the loop's beginning. The problem specifies that all data will be non-negative, so it can initialize max to -1, which is less than all valid input. The program also requires a prompt and read before the loop begins. The prompt and read in the loop body initializes number before using it in the loop test and the if statement. Finally, the program prompts for and reads the next input at the bottom of the loop.