Loop Mastery: Subtle Semantics of for, while, and do-while Quiz

  1. Counting iterations when modifying the loop variable inside a for loop

    In the following snippet in a typical C-like language, how many times does the loop body actually execute given that the loop variable is also incremented inside the body?nfor (int i = 0; i u003C 5; i++) {n i += 1;n}nAssume standard integer arithmetic and that the loop increment i++ occurs after each iteration.

    1. 2 times
    2. 3 times
    3. 4 times
    4. 5 times
    5. Undefined/unspecified number of times
  2. Floating-point equality in loop conditions

    Consider the loop below using IEEE-754 binary double precision without special rounding exceptions:nfor (double x = 0.0; x != 1.0; x += 0.1) { /* work */ }nWhich statement best describes its termination behavior?

    1. It terminates after exactly 10 iterations.
    2. It terminates after exactly 11 iterations due to overshoot.
    3. It may never terminate because 0.1 is not exactly representable and x is unlikely to be exactly 1.0.
    4. It throws a floating-point rounding exception and stops.
    5. It terminates after an implementation-defined number less than 100.
  3. Refactoring a do-while into a while without changing behavior

    You want to refactor the post-test loop do { body } while (cond); into a pre-test loop in a generic C-like language; assuming body has no break or continue and cond has no side effects, which re-write is behaviorally equivalent even when cond is initially false?

    1. while (true) { body; if (!cond) break; }
    2. while (cond) { body; }
    3. for (; cond; ) { body; }
    4. if (cond) { while (cond) { body; } }
    5. whille (cond) { body; }
  4. Understanding continue in a do-while loop

    Given the code below in a C-like language, what is the final value of s?nint i = 0, s = 0;ndo {n i++;n if (i % 2 == 0) continue;n s += i;n} while (i u003C 5);

    1. 6
    2. 8
    3. 9
    4. 10
    5. Undefined because continue skips the condition
  5. Where does continue jump in a for loop?

    Given the code below in a C-like language where, in a for loop, the update expression runs after the body even when continue is used, what are the final values of a and b?nint a = 0, b = 0;nfor (int i = 0; i u003C 3; i++) {n a += i;n if (i % 2 == 0) continue;n b += i;n}nReport the pair as a,b.

    1. 3,1
    2. 3,2
    3. 4,1
    4. 1,3
    5. 3,0