USE C zybooks Ask the user for a number between 3 and 100 in
USE C++ (zybooks)
Ask the user for a number between 3 and 100 (inclusive). USING LOOPS, figure out what is the largest power of 2 that is less than or equal to the number entered. For example, if the user entered 6, answer would be 4. If the user entered 100, the answer would be 64. You must do this within a function called powerOfTwo. For example:
We are only supposed to edit the \"type your code here\" section
#include <iostream>
#include <string>
using namespace std;
/* Type your code here. */
int main()
{
int num;
cout << \"Please enter a number from 3 to 100: \";
cin >> num;
cout << num << endl;
if ((num < 3) || (num > 100))
cout << \"Please follow the directions!\" << endl;
else {
int answer = powerOfTwo(num);
cout << \"The answer is \" << answer << endl;
}
}
Solution
#include<iostream>
#include<math.h> //for pow function
using namespace std;
//Find out the biggest power
void powerOfTwo(int n)
{
int c = 1, p, big = 2;
//Loops till power is less than number
do
{
//Calculates the power of 2
p = pow(2, c);
if(p < n)
{
cout<<p<<\" \";
//find out the biggest power
if(big < p)
big = p;
}
c++;
}while(p < n);
cout<<\"\ The answer is = \"<<big;
}
int main()
{
int no;
cout<<\"\ Please enter a number from 3 to 100: \";
cin>>no;
if(no >= 3 && no <= 100)
powerOfTwo(no);
else
cout<<\"\ ERROR: Please enter a number from 3 to 100: \";
}
Output 1:
Please enter a number from 3 to 100: 100
2 4 8 16 32 64
The answer is = 64
Output 2:
Please enter a number from 3 to 100: 2
ERROR: Please enter a number from 3 to 100:
Output 3:
Please enter a number from 3 to 100: 6
2 4
The answer is = 4

