Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Check whether a given number is a power of two or not

C++ Math: Exercise-1 with Solution

Write a C++ program to check whether a given number is a power of two or not.

Sample Solution:

C++ Code :

#include <iostream>
#include <cmath>
using namespace std;
string Powers_of_Two(int n) {

	for (int x = 0; x < INT_MAX; x++)
	{
		if (pow(2, x) == n)
		{
			return "True";
		}
		else if (pow(2, x) > n)
		{
			break;
		}
	}

	return "False";
}
int main() {
	cout << "Is 8 is power of 2: " << Powers_of_Two(8) << endl;
	cout << "Is 256 is power of 2: " << Powers_of_Two(256) << endl;
	cout << "Is 124 is power of 2: " << Powers_of_Two(124) << endl;
	return 0;
}

Sample Output:

Is 8 is power of 2: True
Is 256 is power of 2: True
Is 124 is power of 2: False

Flowchart:

Flowchart: Check whether a given number is a power of two or not.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: C++ Math Exercises Home.
Next: Write a C++ program to check the additive persistence of a given number.

What is the difficulty level of this exercise?