- C++ program to find factorial using recursive function
- C++ program to convert binary number to decimal and decimal to binary
- C++ program to display prime numbers between two intervals
- C++ program to print Pascal’s and Floyd’s triangle
- C++ program to print star pyramid patterns
- C++ Hello World Program
- C++ program to display Fibonacci series using loop and recursion
- C++ program to find area of the circle
- C++ program to calculate the area of the square with and without using function
- C++ program to encrypt and decrypt the string
- C++ program to convert temperature
- C++ program to check prime number
- C++ program to check palindrome number
- C++ program to make simple calculator using switch case
- C++ program for time conversion (convert time format)
- C++ program to find GCD or HCF
- C++ program to check for the power of two
- C++ program to check Armstrong number
- C++ program to check leap year
- C++ program to find LCM of two numbers

In this program, you will learn about C++ program to check for the power of two with and without using function.

There are various ways to check if a given number is a power of 2. First check below which numbers are the power of two or not.

Numbers that are power of 2: 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048 ... 2^{2}= 4 2^{5}= 32 2^{10}= 1024

We will solve this problem in two different ways:

**Using bitwise operator****Using function**

```
a//C++ program to check whether a number is power of 2 or not
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Enter the number you want to test: ";
cin >> num;
//condition to check whether number is power of two or not
//performing bitwise operation
if((num != 0) && ((num &(num - 1)) == 0))
cout << num << " is a power of 2." << endl;
else
cout << num << " is not a power of 2." << endl;
return 0;
} //end main
```

**Output**

**Explanation**

In the above program, we have used bitwise operators.

**Logic to check if a number is the power of 2.**

If the number is a power of 2 then the bits of the previous number is compliment to the bits that number.

Therefore, if condition compares the bits of number with the previous number.

```
//C++ program to check for the power of using function
#include <iostream>
using namespace std;
//function prototype for checking power of two
int checkPowerofTwo(int n);
int main()
{
int num;
cout << "Enter the number you want to test: ";
cin >> num;
if (checkPowerofTwo(num) == 1)
cout << num << " is a power of 2." << endl;
else
cout << num << " is not a power of 2." << endl;
return 0;
}
//function body
int checkPowerofTwo(int x)
{
//checks whether a number is zero or not
if (x == 0)
return 0;
//true till x is not equal to 1
while( x != 1)
{
//checks whether a number is divisible by 2
if(x % 2 != 0)
return 0;
x /= 2;
}
return 1;
}
```

**Output**

Enter the number you want to test: 20 20 is not a power of 2. Enter the number you want to test: 1024 1024 is a power of 2.