CS110 Lab 13

Looping - Final Review




Part I


1. What output is produced by the following code segment? Modify the code.
int x = 10;
do
        System.out.println("Hello");
while (x > 0);

2. What output is produced by the following code segment?
int x = 10;
do
        System.out.println("Hello");
while (x <= -99);

3. How many times will the following loop execute?
int x = 1;
do {
        System.out.println("Hello");
        ++x;
} while (x >=0);

4. What output is produced by this segment of code?
int number = 0;
int maxNumber = 5;
int sum = 0;
do {
        ++number;
        sum += number;
        System.out.println("Sum is " + sum);
} while (number != maxNumber);
System.out.println("The average of the first " + maxNumber + " positive integers is: " + sum/maxNumber);



Part II


  1. Write a segment of code that will compute the average of any number of test scores using a do-while loop.
  2. Revise the code in problem 1 to employ a while loop.
  3. Revise the code in problem 1 to employ a for loop.



Part III


1. What output is produced by this segment of code? Revise using a do-while loop.
int x= 1;
while (17 % x != 5)
{
        System.out.println(" " + x + " " + 17 % x);
        ++x;
}
2. What output is produced by this segment of code? Revise using a for loop.
int x= 2;
do {
        System.out.println(" " + x + " " + x / 5 );
        x *= 2;
} while ( x != 32);
3. What output is produced by this segment of code? Revise using a for loop.
int x= 1;
int product = 1;
do {
        x++;
        product *= x;
} while ( x < 5);
System.out.println("The product is " + product);
4. What output is produced by this segment of code? Rewrite using a more efficient structure.
int x= -3;
while (x < 3) {
        ++x;
        if (x == 0)
              break;
        System.out.println(x);
}



Part IV: A nested loop


What output is produced by this segment of code?
int x = 0;
while (x < 5) {
        for (int i = 1; i < 5; i++)
            System.out.print(i);
        System.out.print("\n");
        x++;
}



Part V: A Program