Instructional Material: IF Statement Quiz Answers

Printer-friendly version

Since a = 20 and b = 5, the first if statment will compare true and the first branch will be taken setting b to the new value of 2 * b or 10.

The first if looking at c will compare c (10) greater than b (10) and since 10 is not greater than 10 the result is false and the if statement block is not executed.

The second if looking at c will compare c (10) as equal to b (10) the result is true and the if statement block is executed and c is set to 0.

The final if looking at c will compare c (now 0) as less than b (10) the result is true and the if statement is executed leaving c set to 5.4 as its final value.

Is this correct? No. The statement of desired outcome defines what the variable c will be set to depending on it's value. Starting value is implied. But the second if statement changes value of c and then tests c with the third if statement which would not have been true if c had it's starting value.

Coding if statements in a stack like the example opens the door to problems. In this case, the second if operates correctly and sets the value of c to 0 as desired. Based on the statement of outcome we are done. However, since the if statements are in a stack we proceed to look at the next if statement with the new value of c.

Here is the correct code:

float a = 20;
float b = 5;
float c = 10;

if (a > b)
    b = 2 * b;
    b = 0;

if ( c > b)
    c = 100;
else if (c == b)
    c = 0;
else if (c < b)
    c = 5.4;

This code will leave c = 0 which is correct based on the starting value of c = 10.


Material Type: 
Lab Activity
Education Level: 
HW Platform: 
SW Platform: 
Interactivity Style: 
Copyright (c) 2017 by the author. All rights reserved.