While Loop Review

6.5. While Loop Review#

  1. When might you prefer a for loop in place of a while loop? What do you gain?

  2. When might you prefer a while loop or a foreach instead of a for loop?

  3. Describe in general when a foreach loop is going to be easier to use than a while loop.

  4. Each sentence below introduces a problem. What words/combinations suggest a loop/repetition?

    1. Square each number from 1 to n.

    2. Respond until the user says to stop.

    3. Repeat the process until the width is < .00001.

    4. Count the vowels in the sentence that you are given.

    5. See if there are any double letters in the word that you are given.

  5. Compare do-while and while loops: How do you think about which one to use?

  6. In general, what causes an infinite while loop?

  7. A while loop is generally terminated when the program evaluates the condition in its heading and it becomes false. How else can a program exit from a while loop?

  8. When inside a loop, a return statement should generally only appear as a sub-statement of what kind of statement?

  9. Which of these conditions is safer in general, with arbitrary string s and int i?

    s[i] != '#' && i >= 0 && i < s.Length
    
    i >= 0 && i < s.Length && s[i] != '#'
    
  10. What is printed?

int value = 3;
while (value > 0)
{
    Console.WriteLine(value);
    value--;
}
Console.WriteLine("Done");

How would the output change if value started at zero? Explain when the condition is tested.