ADVERTISEMENT
ADVERTISEMENT

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

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.

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;
}

Using User Define 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 »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.