C++ Ask the user for a number between 3 and 100 (inclusive). USING LOOPS, figure
ID: 3857742 • Letter: C
Question
C++
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:
Use this code and just edit it
#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;
}
}
Explanation / Answer
# include<bits/stdc++.h>
using namespace std;
int powerOfTwo(int n)
{
int res = 0;
for (int i=n; i>=1; i--)
{
if ((i & (i-1)) == 0)
{
res = i;
break;
}
}
return res;
}
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;
}
}
======================================================================
akshay@akshay-Inspiron-3537:~/Chegg$ g++ largest.cpp
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Please enter a number from 3 to 100: 6
6
The answer is 4
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.