Fix the Program

Fix the program

The following program takes an integer and counts it towards 0. However, it has an unintended infinite loop. Fix the program by making it stop the counting when it reaches 0.

#include <iostream>

int main()
{
	std::cout << "Input an integer you want to count towards 0.\n";
	int input;
	std::cin >> input;

	while (input <= 0 || input => 0)
	{
		if (input > 0)
			input -= 1;
		else
			input += 1;

		std::cout << input << "\n";
	}
}

Example

4
3
2
1
0
1
0
1
0
1
0
...

Answer

#include <iostream>

int main()
{
	std::cout << "Input an integer you want to count towards 0.\n";
	int input;
	std::cin >> input;

	while (input < 0 || input > 0)
	{
		if (input > 0)
			input -= 1;
		else
			input += 1;

		std::cout << input << "\n";
	}
}

The looping condition was true when our input value was at 0. By changing the operators from <= and >= to < and >, the condition is false when input is 0. We could also do a single check for input != 0.

Questions