CS110 Lab 12

Introduction to the while loop and the do-while loop

1. What is the loop control variable in the code segment shown to the right? Trace through each iteration. What output is produced?
int number = 5;
int sum = 0;
while (number != 0){
        sum += number;
        --number;
}
System.out.println("The sum is " + sum);

2.What output is produced by the code segment to the right?
int number = -4;
int sum = 0;
while (number != 4){
        sum += number++;
}
System.out.println("The sum is " + sum);

3. What output is produced by this segment of code?
int number = 5;
int sum = 0;
while (number != 0){
        if (number % 2 == 1)
              sum += number;
        --number;
}
System.out.println("The sum is " + sum);

4. What output is produced by this segment of code?
int number = 5;
int sum = 0;
while (number > 0){
        if (number % 2 != 1)
              sum += number;
        --number;
}
System.out.println("The sum is " + sum);

5. What output is produced by this segment of code?
boolean isPrime = false;
int number = 500;

do {
        if (number % 251 == 0)
               isPrime = true;
        System.out.println(number--);
} while (!isPrime);


6. What output is produced by the segment of code shown to the right?
final int MAX = 5;
int number = MAX - 1;
int sum = 0;
while (number != MAX)
        sum += number;
System.out.println (" " + num/MAX);

7. What output is produced by the segment of code shown to the right?
final int MAX = 5;
String text = "";
int i = 0;
do {
        text += "AB" + i++;
} while (i < 5);
System.out.println (text);



Part II: Writing Short Programs


  1. Make the following numbers display to the console. Use a while loop. 1 4 7 10 13 16
  2. Make the following numbers display to the console. Use a do-while loop. 20 15 10 5
  3. Write a method that reads in numbers from the keyboard and then when the user enters a -1, gives the average of the numbers. Allow for floating point values.
  4. Write a program that calculates the year in which the population of the US exceeds the population of China, assuming both countries maintain their existing growth rate.