C Program to check given number is power of 2 | Check Power of 2 program


check-power-of-2-program-in-c-language

Program Introduction:

Write a C program to check if the given number is power of 2 or not (detect or check power of 2 program )

Here are couple examples with expected input and outputs

Example 1:

Input:

Output:

Example 2:

Input:

Output:

Example 3:

Input:

Output:

Check Power of 2 program Description:

First of all, Take a variable ‘ result’ and start to calculate all powers of 2 up to the given number and store the largest power of 2 numbers in the ‘ result’ variable. Stop calculating the power of 2 once your ‘ result’ variable reaches the given number.

Then check if the given number matches with our present ‘ result’ variable value.

If the given number and ‘ result’ variable value matches then the given number is Power of 2. Otherwise Given number is not a power of 2.

📢 The result variable default value should be 1, Instead of 0. Because 1 gives us the ability to calculate the power. If you take the default value as 0, Then you can’t calculate the power because anything multiplied by zero is zero.

Also, Our program won’t take any Negative values. If user provides Negative number then we will display the error message. We are not checking the power of 2 for negative values in this program.

Program: Check Given Number is Power of 2 :

Detect power of 2 Program Output:

We are using the GNU GCC compiler to compile our program. I am using the Ubuntu Linux operating system, So please use the IDE which ever you prefer.

Here is a quick tutorial to how to run programs in Linux – Hello World Program in C language – SillyCodes

Conclusion:

In this article, We have discussed about how to calculate the power of 2 in c programming, Also discussed about checking the power of 2 by using the loops.

Related Reading:

Learn more about Power of 2:

Venkatesh

Hi Guys, I am Venkatesh. I am a programmer and an Open Source enthusiast. I write about programming and technology on this blog.

You may also like...

3 Responses

  1. […] C Program to Check Number is Power of 2 […]

  2. […] C Program to Check Number is Power of 2 […]

  3. […] C Program to Check Number is Power of 2 […]

Leave a Reply