Home /
Expert Answers /
Computer Science /
c-programming-will-leave-a-thumbs-up-thank-you-20-points-here-are-four-c-programs-that-cou-pa509
(Solved): C PROGRAMMING
WILL LEAVE A THUMBS UP THANK YOU!
(20 points) Here are four C programs that cou ...
C PROGRAMMING
WILL LEAVE A THUMBS UP THANK YOU!
(20 points) Here are four C programs that count the bits on in an integer; that is, you run './cb 5' and it will print ' 2 ' (because 5 in binary is 101 , and two bits are turned on). For each program, indicate whether it works. If it does not, show how to fix it by changing the fewest characters possible. Note that these programs will crash if not given an argument; that's not considered an error per the design spec. Program A Program C Works as is. ? Needs fixing. Works as is. ? Needs fixing. #include ? stdio.h> #include ? stdlib.h> ? #include ? stdio.h> #include ? stdlib.h> ? int main(int arge, char ?argv[]) int main(int arge, char *argv[]) \{ \{ // warning: assumes argv[1]! // warning: assumes argv[1]! int val=atoi(argv[1]); int val=atoi(argv[1]); int sum =0; int sum =0; for (int i=0;i<32;i++) while ( val ) \{ if (1?i \& val) if (val >0) sum +=1; sum ++ ; val ?<=1; printf("\%d’n", sum ); } \} Program B Program D Works as is. ? Needs fixing. ? Works as is. ? Needs fixing. \#include ?stdio.h> \#include ?stdio.h> int main(int arge, char ?argv[]) int main(int arge, char *argv[]) \{ \{ // warning: assumes argv[1]! // warning: assumes argv[1]! int val = atoi (argv[1]); int val =strtoul(argv[1], NULL, 10) int sum =0; int sum =0; for (int i=31;i>=0;i?? while (val) \{ if ((1?i) \& val ) sum =val \& 1 ; sum +=1; val ?=1; 3 printf( %d\n", sum); \} printf( 1%d\n??, sum); \}
Program A: Works as is. The program takes an integer from the command line argument and counts the number of bits that are turned on in its binary representation. The code uses the bitwise left shift operator (<<) and the bitwise AND operator (&) to check if each bit is turned on.Program B: Works as is. This program also takes an integer from the command line argument and counts the number of bits that are turned on in its binary representation. The code uses the bitwise left shift operator (<<) and the bitwise AND operator (&) to check if each bit is turned on. However, the loop starts from the 31st bit and moves towards the 0th bit to check each bit.Please refer the above steps.