×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

C program to check whether an integer number is power of two (2) or not

Problem statement

In this program, we will read an integer number and check whether the number is Power of Two (2) or not. For example number 12 is the power of two because it the multiple of 2.

Checking whether an integer number is power of two (2) or not

The logic to implement this program - Divide number by 2 until number is not equal to 1, if in the loop remainder is not equal to 0 then number is not power of 2 otherwise number is power of 2.

Check Power of Two (2) using C program

/*C program to check number is power or 2 or not.*/
 
#include <stdio.h>
 
int main()
{
    int num;
    int tempNum,flag;
     
    printf("Enter an integer number: ");
    scanf("%d",&num);
     
    tempNum=num;
    flag=0;
    /*check power of two*/
    while(tempNum!=1)
    {
        if(tempNum%2!=0){
            flag=1;
            break;
        }
        tempNum=tempNum/2;
    }
  
    if(flag==0)
        printf("%d is a number that is the power of 2.",num);
    else
        printf("%d is not the power of 2.",num);
      
    return 0;
}

Checking number is power of two using user-defined function

/*C program to check number is power or 2 or not.*/
 
#include <stdio.h>
 
/*function definition*/
int isPowerOf2(int number)
{
    while(number!=1)
    {
        if(number%2!=0)
            return 0;
        number=number/2;
    }
    return 1;
}
 
int main()
{
    int num;
    printf("Enter an integer number: ");
    scanf("%d",&num);
 
    if(isPowerOf2(num))
        printf("%d is a number that is the power of 2.",num);
    else
        printf("%d is not the power of 2.",num);
     
    return 0;
}

Output

First Run:
Enter an integer number: 32
32 is a number that is the power of 2.

Second Run:
Enter an integer number: 36
36 is not the power of 2.

C Number Manipulation Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.