C Program to Check if a Given Number is a Power of 2 without using Bitwise

This C Program checks if a given integer is a power of 2 without using bitwise.

Here is source code of the C Program to check if a given integer is a power of 2 without using bitwise. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Check if a given Integer is a Power of 2 without using Bitwise
  3.  */
  4. #include <stdio.h>
  5.  
  6. /* function prototype */
  7. int power_of_2(unsigned int);
  8. /* gloabal variables */
  9. int b[32] = {0}, j = 0, n, i, count = 0;
  10.  
  11. void main()
  12. {
  13.     unsigned int num;
  14.  
  15.     printf("enter value\n");
  16.     scanf("%d", &num);
  17.     power_of_2(num);
  18.     if (count == 1)
  19.         printf("YES\n");
  20.     else
  21.         printf("NO\n");
  22. }
  23.  
  24. /* function to check whether a given number is power of 2 or not */
  25. int power_of_2(unsigned int num)
  26. {
  27.     while (num != 0)
  28.     {
  29.         n = num % 2;
  30.         if (n == 1)
  31.             count++;        
  32.         num = num / 2;
  33.     }
  34. }

$ cc bit26.c
$ a.out
enter value
128
YES
 
$ a.out
enter value
126
NO

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.