Home > Articles

0672322765

  • Print
  • + Share This

Workshop

Quiz

  1. The while statement loops as long as a condition is true. What statement loops as long as a condition is false?

    a. if (not ) {}

    b. while (! condition) {}

  2. Is the following expression true or false?

    (0 and 5) || ( ("0" or 0 or "") and (6 and "Hello")) or 1

    a. True

    b. False

  3. What is the value of $i after this loop is run?

    for($i=0; $i<=10; $i++) {	}

    a. 10

    b. 9

    c. 11

Answers

  1. b. The while (! condition ) {} syntax loops until the condition is false.

  2. a. The expression can be reduced in these steps:

    (false) || ( ( false ) and ( true ) ) or true

    false || false or true

    true

  3. c. The test is $i<=10, so when the test is finally false, $i must be 11. If you got this one wrong, don't worry. It's such a common mistake that it even has a special name among programmers: a fence post error or an off-by-one error.

Activities

  • Modify Listing 3.1 to keep playing the game until a successful guess is made.

  • Listing 3.3, as it is written, is actually quite inefficient at finding primes. For example, it analyzes all the even numbers above 2—which cannot possibly be prime. Make additions to the algorithm to make the Primes program more efficient.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.