in Programming in C
406 views
2 votes
2 votes

how does the program is working..?

answer – 8

in Programming in C
406 views

1 comment

$i$ $x$
$5$ $1$
$4$ $1$
$3$ $3$
$2$ $5$
$1$ $8$

the table shows the value of x for each iteration of i.

For more details refer here: GATE CSE 2017 Set 1 | Question: 55

0
0

3 Answers

0 votes
0 votes

The output of the above program will be 3.

The main function contains a for loop that iterates from 5 to 1, and calls the MadeEasy function with each value of i. The MadeEasy function takes an integer as input and returns the number of 1s in the binary representation of that integer.

In each iteration of the for loop, the value of x is updated by adding the return value of the MadeEasy function. Therefore, the final value of x will be the sum of the number of 1s in the binary representation of the integers from 5 to 1.

The binary representation of the integers from 5 to 1 are:

  • 5: 101
  • 4: 100
  • 3: 011
  • 2: 010
  • 1: 001

The number of 1s in the binary representation of each of these integers is:

  • 5: 2
  • 4: 1
  • 3: 2
  • 2: 1
  • 1: 1

The sum of these values is 2 + 1 + 2 + 1 + 1 = 7. However, the for loop starts at i = 5 and ends at i = 1, so the value of x is updated in the opposite order: 1 + 1 + 1 + 2 + 2 = 7.

Therefore, the final value of x is 7, and the output of the program will be 3.

0 votes
0 votes

Ans.

Working:

Note: here count is static means it will be declared only once in the Made Easy function.

main -> loop -> ME(5) --> count:1 return count x=1

main -> loop -> ME(4) --> count:0 return count x=1+0

main -> loop -> ME(3) --> count:2 return count x=1+0+2

main -> loop -> ME(2) --> count:2 return count x=1+0+2+2

main -> loop -> ME(1) --> count:3 return count x=1+0+2+2+3=8

Final Value of x:8    count :3

0 votes
0 votes

static int x = 0;

i = 5 => x = x + MadeEasy(5);

we know (odd number & 1) is 1 and (even number & 1 is 0). 

so, in MadeEasy function, k=5 

count = count + (k&1) ? 1 : -1

=> count = count + (5 & 1) ? 1 : -1 

=> count = 0 + 1 (since 5 & 1 gives 1 that is true.)

=> count = 1; Next K >>= 1; we know it is right shift operator (it divides k with 2^(number of shifts))

=> k = k / 2^1 => k = 5 / 2 = 2;

=> k & 1 is (2&1) which is 0. so,it gives -1. => count = 1 + (-1) = 0 and k = 2 >> 1 => k=1;

=> (1 & 1) is 1. so, it gives 1 count = 0 + 1; Now k becomes 0 and that is false in while, it returns count which is 1.

for i = 4 => k values 4,2,1 which gives -1,-1,1. so, count becomes 1-1-1+1 = 0;

for i = 3 => k values 3,1 which gives 1,1. so, count becomes 0 + 1+1 = 2;

for i = 2 => k values 2,1 which gives -1,1. so, count becomes 2-1+1 = 2;

for i = 1 => k values 1 which gives 1. so, count becomes 2 + 1 = 3;

Therefore, 1 + 0 + 2 + 2 + 3 = 8

edited by