C Puzzles : Questions and Answers - Level 1
Questions
#include#define ABC 20 #define XYZ 10 #define XXX ABC - XYZ void main() { int a; a = XXX * 10; printf("%d\n", a); }
#include#define calc(a, b) (a * b) / (a - b) void main() { int a = 20, b = 10; printf("%d\n", calc(a + 4, b -2)); }
#includevoid main() { int cnt = 5, a; do { a /= cnt; } while (cnt --); printf ("%d\n", a); }
#includevoid main() { int a, b, c, abc = 0; a = b = c = 40; if (c) { int abc; abc = a*b+c; } printf ("c = %d, abc = %d\n", c, abc); }
#includemain() { int k = 5; if (++k < 5 && k++/5 || ++k <= 8); printf("%d\n", k); }
#includevoid fn(int, int); main() { int a = 5; printf("Main : %d %d\n", a++, ++a); fn(a, a++); } void fn(int a, int b) { printf("Fn : a = %d \t b = %d\n", a, b); }
Answers
a = xxx * 10 which is => a = ABC - XYZ * 10 => a = 20 - 10 * 10 => a = 20 - 100 => a = -80
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
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.
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 (.) { .. }.
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.
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
For any further clarifications/ informations and to contribute some more puzzles for this page please feel free to contact Achutha Raman
About me | Publications | C puzzles | Home | Form | Music library | Picture library |