C=10

Could someone please assist. The question here is c?
and I know C = 10. But can someone please explain how that is possible?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

int main() {

int a = 4, b = 2;
int c;
if (a * b > b * 4)
c = 2 * b;
else if (b < a)
c = b + a * 2;
else
c = a;

return c;
}
Did you try tracing the code with pen and paper? Anyway, here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;

int main() {

int a = 4, b = 2;
int c;
if (a * b > b * 4) // if(8>8), then do the next line. 8 > 8 evaluates to
                      // false, so we don't enter the if-clause (next line). 
c = 2 * b;         // this line is never executed, as explained above

else if (b < a)   // we check this condition now. 2 is less than 4. 
                     // this evaluates to true, so we enter the if-clause                   
c = b + a * 2; // c = 2+(4*2) = 10

else                // this else clause is never executed, as the previous
c = a;             // else-if has already been executed

return c;    // c = 10
}
Last edited on
Thank you that made so much sense. I appreciate it. Its actually much simpler...just see which one is the only if statement that can be true and go with it.
Topic archived. No new replies allowed.