Scope, Precedence & While-loops

  1. Determine if the following code fragments breaks scope rules.
int x = 0;
if (x == 3)
    int y = 1;
y = 2;
int x = 0;
while(x < 10) {
    int y = 0;
    if (y < 10)
        y++;
    y = 5;
    x++;
}
int x = 0;
while (x < 10) {
    if (x == 2)
        int y = 4;
    if (x == 3)
        int y = 5;
    x++;
}
  1. List the precedence of the following operators.

(), =, ++, --, |, *, /, %, &, +, -, ==, !=, >, <, >=, <=

  1. Write a while loop that prints the numbers between 1 and 100, each on a new line.
  2. Write a while loop that sums the numbers 2, 4, 6, 8, …, 100.
  3. Write a while loop that counts the number of integers between 1 and 100 that are divisible by 3.
  4. Write a fragment of code that has an infinite-loop. Within the loop, the program asks the user to enter an integer then reads in the integer.   If the value of the number read is 0, the program exits the loop, otherwise the program continues in the loop.
  5. Write a while loop that adds the first k numbers of the Fibonacci sequence: {1, 1, 2, 3, 5, 8, 13, 21, …}.

© 2017, Eric. All rights reserved.