Write a while loop that prints userNum divided by 2 (integer division) until reaching 1. Follow each number by a space. Example output for userNum = 40:
20 10 5 2 1
.....
my code:
#include <iostream>
using namespace std;
int main() {
int userNum;
userNum = 40;
/* Your solution goes here */
while (userNum != 1){
userNum = userNum/2;
cout << userNum << " ";
}
cout << endl;
return 0;
}
........
but as a result i keep getting : "Program end never reached. This is commonly due to an infinite loop or infinite recursion."....fix this?
The detailed solution is provided below:
The corrected code (based on the code provided in the question) is presented below:
#include <iostream>
using namespace std;
int main() {
int userNum;
userNum = 40;
/* Your solution goes here */
//the while loop will be executed as long as the userNum is
greater than or equal to 1
while (userNum >= 1){
userNum = userNum/2;
cout << userNum << " ";
}
cout << endl;
return 0;
}
Output: (As obtained from the console window)
20 10 5 2 1
So, actually in the original code provided by you, the loop was running infinitely as long as unserNum is not equal to 1. There has been a slight change. The condition will be >=1.
Hope this helps.
Get Answers For Free
Most questions answered within 1 hours.