Program to check whether a number is power of 2 or not - C

Solution of Book : A textbook of C programming, page : 194, qno:29

Q. Write a program to check whether a number is power of 2 or not.

==> To solve this problem we have used while loop as well as remainder operator. 

Let's jump into the coding:
Code goes like this: 

#include <stdio.h>
int main()
{
    int num;
    int temp,flag;

    printf("Enter an integer number: ");
    scanf("%d",&num);
    temp=num;
    flag=0;
    while(temp!=1)
    {
        if(temp%2!=0){     //
            flag=1;
            break;
        }
        temp=temp/2;  
    }
    if(flag==0)
        printf("%d is  power of 2 ",num);
    else
        printf("%d is not power of 2 ",num);

    return 0;
}

Output: 


If you see above output, we have entered 16 as a input and the output is "16 is power of 2" which is true. 

Now, let's take a look, how the whole program works. 

1. First of all we have taken input in num variable and stored it's value to temp as well.
2. In case of 16, it goes inside while loop because it's not equal to 1. 
3. When we take remainder it's equal to 0 so, it doesn't touch the flag 1 part.
4. 16/2=8, while loop still true. So, it repeats step 3 with 8.
5. 8/2=4, while loop still true. So, it repeats step 3 with 4.
6.4/2=2,while loop still true. So, it repeats step 3 with 2.
7.2/2=1, while loop false, so loop breaks here.
8. flag 1 part is not touched so, it's the condition of flag 0
9. prints 16 as power of 2.


Output1: 

Now if we see with this number (i.e. 12), how the program works? 
1. First of all we have taken input in num variable and stored it's value to temp as well.
2. In case of 12, it goes inside while loop because it's not equal to 1. 
3. When we take remainder it's not equal to 0 so, it executes the flag 1 part and breaks the loop
4. prints 12 as not power of 2 due to flag 1(i.e. else flag).

So, in this way, we solved and executed this problem successfully. 
We have used Code blocks IDE for this program. If you have any queries regarding this, you can leave a comments as well. 

stay Safe! stay Positive ! 
Thank you.
Share on Google Plus

About Nepali Xoro

Interested in Information Technology, Spreading Knowledge for Nepalease IT Students."Loves Traveling", Listen Music and Surfing web.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment