Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! ๐ ๐นLearn advanced coding techniques in C& C++ ๐นMaster Linux internals & shell scripting ๐นDeep dive into Data Structures & Algorithms ๐นExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) ๐นGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
C program to check whether a given number is a power of 2 using bitwise operations
⚡ Check If a Number Is a Power of 2
#include<stdio.h>
int power(int num)
{
if(num > 0 && (num & (num - 1)) == 0)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int num;
scanf("%d", &num);
if(power(num))
{
printf("%d is a power of 2\n", num);
}
else
{
printf("%d is not a power of 2\n", num);
}
}
๐ Explanation:
✅ The condition (num & (num - 1)) == 0 is true only if there is only one set bit in num.
✅ This logic efficiently checks whether a number is a power of 2.
✅ It excludes 0 and negative numbers.
๐งช Sample Output:
Input:
8
Output:
8 is a power of 2
๐ท️ Keywords:
C program power of 2, bitwise check power of 2, efficient logic, beginner C programming, technical interview questions
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment