| Author |
C quiz questions
|
sovan chatt
Ranch Hand
Joined: Aug 09, 2010
Posts: 43
|
|
I need help with the following questions in
1)
output?
2)
I felt the answer would be 21,13,13,13 but the answer is 22,13,13,13.How b is coming as 22?
3)
I felt the answer should be 0, 1, 2, 3, 4, but is 0,0,1,2,3,4.How is the extra 0 coming?
4) why does 11 ^ 5 show 14
5)here a should have been 13(5*2+3) but it is coming as 25.How?
6)Why is this creating an infinite loop?
|
 |
Mary Chellapa
Ranch Hand
Joined: Jul 26, 2011
Posts: 93
|
|
|
1. output = 10
|
Mary
|
 |
Mary Chellapa
Ranch Hand
Joined: Jul 26, 2011
Posts: 93
|
|
|
wow i could answer only first ... and i thought i was good in C.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3050
|
|
Note that most of the answers are actually undefined, because C doesn't have proper rules for order of evaluation.
That said, here are some explanations using left-to-right evaluation.
1.)
z = x++ - --y * b / a;
z = 5++ - --(-10) * 2 / 4;
z = 5 - (-11) * 2 / 4;
z = 5 - (-22) / 4;
z = 5 - (-5);
z = 10;
2.)
b = a++ + ++a;
b = 10 + 12; // a = 12;
b = 22;
printf("%d,%d,%d,%d", b, a++, a, ++a);
printf("%d,%d,%d,%d", 22, 12, 13, 14);
3.)
myFunc(5) -> myFunc(4); printf("%d, ", 4);
myFunc(4) -> myFunc(3); printf("%d, ", 3);
myFunc(3) -> myFunc(2); printf("%d, ", 2);
myFunc(2) -> myFunc(1); printf("%d, ", 1);
myFunc(1) -> myFunc(0); printf("%d, ", 0);
myFunc(0) -> printf("%d, ", 0);
4.)
^ is the binary XOR operator. The calculation goes like this:
00001011 // 11
00000101 // 5
________
00001110 // 11 xor 5 = 14
5.)
Assignment operators (including compound assignment, like *=) have lowest precedence. The calculation goes:
a *= 2+3;
a *= 5;
a = 5*5;
a = 25;
6.)
You get an infinite loop because you're never incrementing the loop variable i. You're passing i to the increment function by value. The function increments a copy of i, and leaves the original variable like it was. A working increment function would look like this:You would call it like this:
|
 |
sovan chatt
Ranch Hand
Joined: Aug 09, 2010
Posts: 43
|
|
@Stephan van Hulst thanks for the explanations!.
I have got 1 more question.
if I insert 358 and 453 what will x and y hold?
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
The correct answer to that is "try it yourself and find out".
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: C quiz questions
|
|
|