Problem 5 Solution: Average With A While-Loop

Both solutions have a test controlling the loop, but they place the text in different locations. The first solution is a "normal" while-loop, incorporating the test into the while statement. The second solution creates an infinite loop and implements the test as an if-statement placed in the loop body.

Function 1

The first solution requires two prompt and read operations. The first occurs before the program enters the loop, initializing number before the loop test uses it. The second input occurs inside the loop at the bottom, ensuring number is ready for testing at the beginning of each subsequent iteration.

double ave2()
{
	double	sum = 0;
	int	count = 0;
	int	number;

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

	while (number >= 0)
	{
		sum += number;
		count++;

		cout << "Enter a number: ";
		cin >> number;
	}

	if (count > 0)
		return sum / count;
	else
		return -1;
}
ave2 version 1: while-loop based function calculating a mean or average.

Function 2

The second solution uses an infinite loop, eliminating the need to initialize number before the loop begins. This modification allows the function to work with a single prompt and read operation at the top of the loop body. Although this version requires a nested if-statement, it replaces the loop test, so when compiled to machine code, it shouldn't significantly increase the loop size or execution time. Either version works, and you will see both in practice.

double ave2()
{
	double	sum = 0;
	int	count = 0;
	int	number;

	while (true)
	{
		cout << "Enter a number: ";
		cin >> number;

		if (number < 0)
			break;

		sum += number;
		count++;
	}

	if (count > 0)
		return sum / count;
	else
		return -1;
}
ave2 version 2: while-loop based function calculating a mean or average.