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

Programming and data structure miscellaneous

Programming & Data Structure

  1. Consider the following C-program :
        void foo (int n, int sum) {
       int k = 0, j = 0
       if (n = = 0) return;
       k = n% 10, j = n/10;
       sum = sum + k;
       foo (j, sum);
       printf (“%d”, k);
    }
    int main () {
        int a = 2048, sum = 0;
       foo (a, sum);
       printf (“%d\n”, sum);
    What does the above program print?
    1. 8, 4, 0, 2, 14
    2. 8, 4, 0, 2, 0
    3. 2, 0, 4, 8, 14
    4. 2, 0, 4, 8, 0
Correct Option: D

Sum has no use in foo(), it is there just to confuse. Function foo() just prints all digits of a number. In main, there is one more printf statement after foo(), so one more 0 is printed after all digits of n.
From the given code it is found that foo is a recursive function and when the function foo (a, sum) is called where a = 2048 and sum = 0 as per given conditions.
Then, the execution of the function takes in the following manner.
i) k= n% 10 => modulus operator will return the remainder. for example, if n = 2048, then 2048 %10 will store the value 8 in k.
ii) j is declared as integer datatype in foo function. Therefore after division if the result contains decimal part, it will be truncated and only the integer part will be stored in j. For example if j = 2048 / 10, (actual result = 204.8) then 204 will be stored in j.
iii) The sum variable declared in the main function will not be used by the foo function.



Your comments will be displayed only after manual approval.