Home » Programming & Data Structure » Programming and data structure miscellaneous » Question

Programming and data structure miscellaneous

Programming & Data Structure

  1. The output of executing the following C program is _______.
    #include
    int total (int v) {
        static int. count = 0;
       while (v) {
        count + = v&l;
        v >>= 1;
       }
       return count;
    }
    void main() {
       static int x = 0;
       int. i = 5;
       for (; i > 0; i --) {
       x = x + total (i);
       }
       printf (“%d\n”, x);
    }
    1. 23
    2. 32
    3. 12
    4. 21
Correct Option: A

Count in the function Total is static :

Check out the running code with comments
for (i = 5; i > 0; i – –)
x = x + total (5);
   While (5)    ( ∴ v = 5)
Count = Count + V & 1
   = Count + 5 & 1       (5 & 1 = 1)
Count = Count + 1        (Count = 1)
if (V = 2) Count = 1 + 2 & 1 = 1 + 0 = 1
if (V = 1), count = (1 +(1 & 1)) = 1 + 1
Count = (1 + 1) = 2
Return (2);
Then, X = 2 + total (4):
    Ccunt = (2 + (4 & 1)) = 2 + 0 = 2
    (∴ 2 is static)
If (V = 2)
Count = (2 + (2 & 1)) = 2 + 0 = 2
if (v = 1)
Count = (2 + (1 & 1)) = 3
Count = 3

return (3)

X = ((2 + 3) + total (3);)
    (∵ 2 is static)
X = (5 + total (3);)
(∵5 is static)
So, count = (3 + (3 & 1)) = 3 + 1 = 4
    If (V = 2)
    Count = (4 + (2 & 1)) = 4 + 0 = 4
    If (V = 1)
    Count = (4 + (1 & 1)) = 4 + 1 = 5
    Count = 5
return (5)

X = (5 + 5) + total (2);
(∵5 is static)
X = (10 + total (2);)
(∵ 10 is static) so, count = 6
return (6) ;

X = (10 + 6) + total (1);)
(∵ 10 is static) so, count = 7
return (7) ;

= 16 + total (1);
(∵ 16 is static), so count = 16 + 7 = 23 (static)
(∵7 is static)
Hence in the function Total count static is: 23.



Your comments will be displayed only after manual approval.