Revision Exercises - Iteration, part 2

These revision exercises are provided to give you some extra practice with the basic programming concepts covered in the first semester, especially those that people had difficulty with on the test. The first exercise set covers iteration: for, while and do loops.

Solutions to the exercises will be available a week or two after the exercises are posted on the Web.


1. More triangles, and some other shapes too

Repeat questions 1-10 of the previous exercise set, but this time your answers should use only while loops.

2. Counting iterations

How many times is the body of each of the following loops executed? The answer is not necessarily a particular known value; it may depend on some of the other variables. You may assume that all variables are of type int unless they are declared otherwise.
 
 
11.
int i = 0;
while (i < 100) {
  // body
  i++;
}
12.
int i = 17;
while (i <= 56) {
  // body
  i++;
}
13.
int i = 0;
while (++i < 100) {
  // body
}
14.
int i = 0;
while (i++ < 100) {
  // body
}
15.
int i = 3;
while (++i < 52) {
  int j = 0;
  while (j++ < 10) {
    // body
    i++;
  }
}
16.
int i = 0;
while (i < x) {
  // body
  i += 2;
}
17.
int i = 0;
while (i++ < x) {
  int j = i;
  while (j++ < y) {
    // body
  }
}
18.
int i = x;
while (i >= y) {
  // body
  j--;
}
19.
int i = 42;
while (i > 42) {
  // body
  i++;
}
20.
int i = 0;
while (i <= 1024) {
  // body
  i *= 2;
}

Scott Mitchell

Last modified: February 3, 1999