//This program will prompt for an integer between 1 and 30, inclusively, and the
ID: 640469 • Letter: #
Question
//This program will prompt for an integer between 1 and 30, inclusively, and then repeatedly divide the number by 2 until the number reaches 1 or less.
//Each time, print the value of the number before the division by 2 is done.
//For example, if 20 was entered, the output will be : 20 10 5 2 1
#include <iostream>
using namespace std;
int main() {
int userNum = 0;
//prompt for and read an int value to userNum
cout << "Enter a value: " << endl;
cin >> userNum;
//Test if value entered is < 1 or > 30 then display error message
//and get out of program
//if valid, print the value entered and
// then divide this value by 2.
// Print this new value after division, and keep
// doing this until the this new value is equal to 1
cout << endl;
return 0;
}
------
Help. I am lost with the loops.
Explanation / Answer
#include <iostream>
using namespace std;
int main(){
int userNum = 0;
//prompt for and read an int value to userNum
cout << "Enter a value: " << endl;
cin >> userNum;
//Test if value entered is < 1 or > 30 then display error message
//and get out of program
if(userNum < 1 || userNum > 30){
cout << "Error: value entered is < 1 or > 30" << endl;
return 0;
}
//if valid, print the value entered and
// then divide this value by 2.
// Print this new value after division, and keep
// doing this until the this new value is equal to 1
while(userNum != 1){
cout << userNum << " ";
userNum = userNum / 2;
}
cout << userNum << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.