Thursday, October 28, 2010

C Puzzles Part 2

Questions 

L1.Q1 : Write the output of the following program 

#defineABC     20
#define XYZ    10
#define XXX    ABC - XYZ
void main()
{
        int     a;
        a = XXX * 10;
        printf("%d ", a);
}


L1.Q2 : Write the output of this program 

#define calc(a, b)     (a * b) / (a - b)
void main()
{        int a = 20, b = 10;
         printf("%d ", calc(a + 4, b -2));
}

L1.Q3 : What will be output of the following program ? 

void main()
{
         int cnt = 5, a;
         do {
               a /= cnt;
        } while (cnt --);
        printf ("%d ", a);
}

L1.Q4 : Print the output of this program 

void main()
{
        int  a, b, c, abc = 0;
         a = b = c = 40;
         if (c) {
               int abc;
               abc = a*b+c;
        }
        printf ("c = %d, abc = %d ", c, abc);
}

L1.Q5 : Print the output of this program 

main()
{
        int k = 5;
        if (++k < 5 && k++/5 || ++k <= 8);
        printf("%d ", k);
}


L1.Q6 : What is the output of this program ? 

void fn(int, int);
main()
{        int     a = 5;
         printf("Main :  %d %d ", a++, ++a);
         fn(a, a++);
}
void fn(int a, int b)
{
       printf("Fn : a = %d b = %d ", a, b);
}


Answers 

L1.A1 


a = xxx * 10  
which is => a = ABC - XYZ * 10
        => a = 20 - 10 * 10
        => a = 20 - 100
        => a = -80

L1.A2 


Actual substitution is like this :
calc(20+4, 10 -2) is calculated as follows 
(20+4 * 10-2) / (20+4 - 10-2)
(20+40-2) / 12
58 / 12  = 4.8 
since  it is printed in %d the ans is 4

L1.A3 


This  problem  will compile  properly,  but it will give run
time error.  It will give divide-by-zero  error.  Look in to
the do loop portion

        do { a /= cnt; } while (cnt --);

when the 'cnt' value is 1, it is decremented in 'while
( cnt --)' and on next reference of 'cnt' it becomes zero.

        a /= cnt;  /* ie. a /= 0 */
which leads to divide-by-zero error.

L1.A4 


the result will be c = 40 and abc = 0;
because the scope of the variable  'abc' inside if(c) {..  }
is not valid out side that if (.)  { ..  }.

 
L1.A5 


The answer is 7.  The first condition ++k < 5 is checked and
it is false  (Now k = 6).  So, it checks  the 3rd  condition
(or condition ++k <= 8) and (now k = 7) it is true.  At this
point k value is  incremented by twice, hence the value of k
becomes 7.  

L1.A6 

The  solution  depends  on  the   implementation  of  stack.
(Depends on OS) In some  machines the  arguments  are passed
from left to right to the  stack.  In this  case the  result
will be


        Main :  5 7 Fn :  7 7 

Other  machines  the  arguments  may be passed from right to
left to the stack.  In that case the result will be
       Main : 6 6
       Fn   : 8 7

No comments:

Post a Comment