The following program is used to check if a given number is the power of 2 using
ID: 3809832 • Letter: T
Question
The following program is used to check if a given number is the power of 2 using bitwise operator. #include define NUM_BITS_INT (8*sizeof(int)) int power2(unsigned int x) { int i, count = 0, result, shift_num; for (i = 0;i > i; result = shift_num & 1; if (res = 1) count++; } if (count % 2 -- 1) printf("YES"); else printf("NO"); } int main () { unsigned int num; printf(" Enter Number"); scanf("%d", num); this.power2(num); return 0; } Which line(s) is(are) incorrect? And how to correct it(them)? Please write down your correction for that line (those lines).Explanation / Answer
/*Note: please read the comments carefully for better understanding */
#include <stdio.h>
#define NUM_BITS_INT (8*sizeof(int))
int power2(unsigned int); //correct line- here function needs to be declared first
int main()
{
unsigned int num;
printf(" Enter Number");
scanf("%d", &num);
power2(num);
}
/*
* Finding the power of 2 using bit wise operators
*/
int power2(unsigned int x)
{
int i, count = 0, result, shift_num;
// for (i = 0;i <= NUM_BITS_INT;i++)incorrect line
for (i = 0;i < NUM_BITS_INT;i++) /* correct line -1. here i should increment by 1(i.e i++) in each step instead of i--
2. we have to execute the statment upto 8 times as we have started from 0 so it should <NUM_BITS_INT instead of <= NUM_BITS_INT
*/
{
shift_num = x >> i;
result = shift_num & 1;
// if (res == 1) incorrect line
if (result == 1) // correct line -here it should be result instead of res
count++;
}
/*
*If number of bits set to 1 are odd then the number is power of 2
*If number of bits set to 0 are even then the number is not power of 2
*/
// if(count %2==1) incorrect line
if (count == 1) // correct line- here it should be count ==1 instead of count moudulo by 2 equal to 1
printf("YES");
else
printf("NO");
}
/* alternate & easiest way to do the same thing. you can use the below power2 function instead of upper one mentioned*/
/*
* Finding the power of 2 using bit wise operators
*/
int power2(unsigned int x)
{
if ((x&(x-1))== 0)
printf("YES");
else
printf("NO");
}
//Please give me thumbs up, if you like my work.:)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.