C Programming - Bitcount Assignment



Number of bits in the binary representation of an integer number N, is the number of times you need to divide N by 2 until it is strictly less than 1. For example: If N = 0  The binary representation of 0 (0) has 1 digit (one division by 2). If N = 2  The binary representation of 2 (10) has 2 digits (two divisions by 2). If N = 5  The binary representation of 5 (101) has 3 digits. If N = 72  The binary representation of 72 (1001000) has 7 digits. If N = 1000  The binary representation of 1000 (1111101000) has 10 digits. a) Write a program that asks the user to enter an integer number (num) between 0 and 1000. Then, it uses a while loop to compute and display the number of times you need to divide num by 2 until it is strictly less than 1. b) Your program should make sure that the user input is in the valid range (between 0 and 1000). c) Save your program to a file named “bitCount.c” in the working directory on the PC you are using. d) Demonstrate the bitCount.c file to GA/TAs and run with different input values. A sample interaction is shown below: Enter a number between 0 and 1000: 2 The binary representation of 2 has 2 digit(s). Enter a number between 0 and 1000: 72 The binary representation of 72 has 7 digit(s). Enter a number between 0 and 1000: 1002 Invalid input

#include<stdio.h>
int main(void){
   int n,s;
   int count=0;
   printf("Enter a number between 0 and 1000:\n");
   scanf("%d",&n);
   if(n==0) {
       printf("The binary representation of 0 has 1 digit.\n");
return 0; }
   s=n;
   if(n<0 || n>1000) {
           printf("Invalid input\n");
           return 0;
   }
   while(n>0) {
           count++;
           n=n/2;
   }
   printf("The binary representation of %d has %d digit(s).\n",s,count);
 return 0; }

Comments