Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   multiple choice q/a doubt (http://www.go4expert.com/forums/multiple-choice-q-doubt-t6217/)

buddy 5Sep2007 20:42

multiple choice q/a doubt
 
Code:

int z,x=5,y=-10,a=4,b=2; z=x++ - --y*a/b
for this program the answer was given as 12 but when i tried to run this program it gave output of 10.

Can any one explain this?? i saw this code in a thread heading 100 multiple choice questions.

DaWei 5Sep2007 21:38

Re: multiple choice q/a doubt
 
Neither of your answers is correct. Perhaps you copied the code incorrectly. You certainly have an error in the posted material: a missing semicolon.

Cramming a bunch stuff on one line is not good practice. It doesn't make your code shorter. It doesn't make your code faster. It doesn't make your code more readable. It's the act of a novice or a schlock.

shabbir 5Sep2007 21:40

Re: multiple choice q/a doubt
 
Try evaluating and see what is the order and then try to come up with an explanation that the compiler is behaving in such a manner.

Also if you have some thing else as the answer the original answer could be wrong also.

buddy 5Sep2007 21:46

Re: multiple choice q/a doubt
 
hi dawei&shabbir,

first i had writen code in code block for first time so this kind of confusion,actually i had written code in both Turboc++ and UNIX in step by step only without any error.it compiled without error.Both gave output of 10.can u plz explain the equation,what will happen when z=x++ - --y*a/b; executes.???

Plz.

shabbir 5Sep2007 21:49

Re: multiple choice q/a doubt
 
I also Ran and saw that it should be 10. Need to make that correct in that thread.

buddy 5Sep2007 22:00

Re: multiple choice q/a doubt
 
[CODE]Z = x++ - --y*b/a;
Z= 5++ - -- -10*2/4;
Z= 10;

Thank you shabbir,but in second line -- -20/4 gives -5 which is decremented to -6 then,x++ increments but remains 5 then the answer should be 11.why was it giving 10.??

DaWei 6Sep2007 00:11

Re: multiple choice q/a doubt
 
The first expression, x++, will evaluate to 5 because it isn't incremented until afterwards.
The second expression, --y, will evaluate to -11.
The multiplication will be performed before the subtraction, thus -11 * 4 / 2 = -22
Then, 5 - -22 = 27.

If you compile and run the code, you will get 27.

Code:

#include<iostream>
using std::cout;
using std::endl;

int main()
{
    int z,x=5,y=-10,a=4,b=2; z=x++ - --y*a/b;
    cout << "The result is " << z << endl;
    return 0;
}

Quote:

Originally Posted by Output
The result is 27


buddy 6Sep2007 00:18

Re: multiple choice q/a doubt
 
hi dawei,

Thanks for your help.i will execute the code and get back to you tomorrow.bye

buddy 6Sep2007 19:16

Re: multiple choice q/a doubt
 
hi DaWei,

i have executed your code understood well .Thanks for your explaination.

Regards.


All times are GMT +5.5. The time now is 22:06.