What is the value of sum? and why?

sum = 0
num = 10

if (num > 5)
sum = sum + 10;
else
if (num = 10)
sum = num = 15;
sum = sum + num


answers:
a= 0
b= 20
c= 10
d= 25

I gave "C" (10) as an answer, but i was wrong.. can you tell me what the answer is and why ? thanks

Look more carefully at the if statements. This is why indentation is important to making code easy to understand.
Try making the code more readable and it should be obvious:

1
2
3
4
5
6
7
8
9
10
11
12
13
sum = 0;
num = 10;

if (num>5)
{
    sum = sum + 10;
}
else if (num==10) //assuming you meant "=="
{
    sum = sum + num;
}

sum = num + sum;


Now try and figure out what gets ran and what doesn't.
I think I got it... the "if" is True, so the first statement applies...meaning sum=10, then "else" is by passed, and then sum = 10 +10
that is .. sum=20 right ?
That's the answer I came up with.
20 is correct. You could always compile and run the code as well :p (provided you aren't still in the middle of the test)
Thanks guys for your help...and no...I wasn't in the middle of a test :O)
Topic archived. No new replies allowed.