Skip to main content

Featured

C Pattern Programs: Square Number and Alphabet Patterns Explained

πŸ”· Square Star Pattern πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = 1; i <= num; i++) { for(int j = 1; j <= num; j++) { printf("* ");//keep"* " } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Column-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; printf("Enter the number:\n"); scanf("%d", &num); for(int i = num; i >= 1; i--) { for(int j = num; j >= 1; j--) { printf("%c ", j + 64);//%c for Character and 64 will be ASIIC VALUE } printf("\n"); } return 0; } πŸ”· Reverse Square Alphabet Pattern (Row-wise) πŸ“‹ Copy Code #include <stdio.h> int main() { int num; ...

C program to check whether a given number is a power of 2 using bitwise operations

Check Power of 2 in C

⚡ 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

Comments

Popular Posts

πŸŒ™