Fix the program 2
Similarly to 1.5.2-1 this program takes an integer and counts it towards 0. However, it counts at a factor of 2.
This makes odd numbers not reach 0 properly, which leads to an unintended infinite loop. Fix the program by making it reach 0 on the last count.
#include <iostream>
int main()
{
std::cout << "Input an integer you want to count towards 0.\n";
int input;
std::cin >> input;
while (input != 0)
{
if (input > 0)
input -= 2;
else
input += 2;
std::cout << input << "\n";
}
}
Example
4
2
0
5
3
1
-1
1
-1
1
-1
1
-1
...
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)
{
// If the current value is higher than 2 we always want to decrement it by 2
if (input >= 2)
input -= 2;
// The same thing goes if it's smaller than -2
else if (input <= -2)
input += 2;
// At this point the input is either 1 or -1. Either way the next value `input` should have is 0.
else
input = 0;
std::cout << input << "\n";
}
}
By adding an if chain like this we make sure that the program functions like normal (counting with a factor of 2) untill the number is between 2 and -2, at which point we set it to 0, completing the loop.