Discussion
Which of the following statements are correct about the program?
#include <stdio.h>
int main()
{
unsigned int num;
int c=0;
scanf("%u", &num);
for(;num;num>>=1)
{
if(num & 1)
c++;
}
printf("%d", c);
return 0;
}
Answer: A
Correct answer: It counts the number of bits that are ON (1) in the number num.
The loop is the standard population count. Each pass tests the lowest bit with num & 1, incrementing c when it is set, then shifts num right by one so the next bit takes that position.
The loop condition num stops as soon as the value reaches zero, so it runs once per significant bit rather than a fixed number of times. Declaring num unsigned matters: right-shifting a negative signed value propagates the sign bit and the loop would never terminate.
No comment is present. Be the first to comment.
Loading…
Post your comment
Please log in or register to post a comment.
Examination Categories
- SSC Exams
- Banking Exams
- Teaching Exams
- Civil Services Exams
- Railways Exams
- Engineering Recruitment Exams
- Defence Exams
- State Government Exams
- Police Exams
- Insurance Exams
- Nursing Exams
- Other Government Exams
- NRA CET
- PG Entrance Exams
- Campus Placement
- MBA Entrance Exams
- CUET and UG Entrance
- Judiciary Exams
- Regulatory Body Exams
- Software Development