Tut 03 - More on Conditionals

Thanks for my tutor Eric Han!

Problem Set 9

Problem 9.1

Problem 9.1(a)

In the snippet of code, we can easily find out that a counterexample is a=b=c0a=b=c\neq0. Our program will output 0. That's incorrect.

Problem 9.1(b)

To find all the test cases that the function would fail, we can start from the counterexample we have given in Problem 9.1(a).

What if any two of these three numbers are equal and not zero?

Let's say a=b0a=b\neq0. That means all the if conditions that contain a==b will output false and due the the short-circuiting property of the && operator, the first two conditions won't pass and max is still 0. Now we have only one condition remaining. How to make it "false"?

If cc is bigger than both aa and bb, then max will be cc, our function will output the correct answer. But think it reversely, if cc is less than aa and bb, our max will be zero and the actual max should be either aa or bb.

Now, we have come to one of our solutions, that's when 0a=b>c0\neq a=b>c, our function will output wrongly.

Similarly, we can get the other two conditions

  1. 0b=c>a0\neq b=c>a

  2. 0a=c>b0\neq a=c>b

Adding the counterexample from Problem 9.1(a), we have written all the cases when our function will output wrongly.

Problem 9.2

To solve this question, we should form our "truth table" first

vac(p)
vac(q)
child(p)
child(q)
same_household(p,q)

yes

yes

dc

dc

dc

yes

no

dc

yes

yes

no

yes

yes

dc

yes

no

no

yes

yes

yes

Then, we use this table to form our code

if (vac(p) && vac(q))
    return true;
if (same_household(p, q))
{
    if (vac(p) && child(q))
        return true;
    if (vac(q) && child(p))
        return true;
    if (child(p) && (child(q))
        return true;
}
return false;

Problem Set 10

Problem 10.1

  1. (x1)(y==10)(x\leq1)||(y==10)

  2. eating!drinkingeating || !drinking

  3. (!has_cs2030(!has\_cs2030 && !has_cs2113)!has_cs2040c!has\_cs2113) || !has\_cs2040c

Problem 10.2

long score = 4;
if (something) {
  score = 10;
} else {
  score = 0;
}
// { score == 0 || score == 10 }

if (score == 4) {
    score = 1;
} else {
    score += 10;
}
// { score == 20 || score == 10 }

if (score >= 10) {
    cs1010_println_string("ok");
} else {
    cs1010_println_string("failed");
}

Based on the assertion we have derived in the comment in the code above, we can safely say the string "ok" will be printed.

What's the use of assertion

Assertion can not only help us get a better view of our code flow, but can also help us find the dead code (the code that will never be executed) in our program. For example, in Problem 10.2, our dead code will be the condition that judge whether our score will be 4.

Last updated