Java Exercises: Loops

Instructions: Complete these exercises on paper first. Then run the code to check your answers. Bring questions about these problems to your next class.

  1. What is the minimum number of iterations a while, do..while and for loop can make?
  2. What is wrong with the following loop:
    while (n <= 100) {
        sum += n*n;
    }
        
  3. How can a loop be structured so that it terminates with a statement in the middle of its block?
  4. Modify the following code so that it uses a while loop to compute factorials.
    import javax.swing.*;
    
    public class Factorial {
      public static void main(String args[])
      {
         int n;
         int factorial = 1;
         String input;
         String output;
    
         input = JOptionPane.showInputDialog ("Enter a positive integer: ");
         n = Integer.parseInt(input);
         output = "" + n;
    
         do {
             factorial *= n;
             n--;
         } while (n > 1);
    
         output += "! = " + factorial;
         JOptionPane.showMessageDialog(null, output);
         
         System.exit(0);
       } // main
    } // Factorial
      
  5. Modify the program above so that it uses a for loop to compute factorial.
  6. Convert the following for loop into a while loop:
    for (int i = 1; i <= n; i++) {
        System.out.println(i*i);
    }
      
  7. Describe the output of the following code:
    for (int i = 0; i < 8; i++) {
        if (i%2 == 0) System.out.println(i + 1);
        else if (i%3 == 0) System.out.println(i * i);
        else if (i%5 == 0) System.out.println(2*i - 1);
        else System.out.println(i);
    } // for
      
  8. Describe the output of the following code:
    for (int i = 0; i < 8; i++) {
        if (i%2 == 0) System.out.println(i + 1);
        else if (i%3 == 0) continue;
        else if (i%5 == 0) break;
        System.out.println("End of Loop");
    } // for
    System.out.println("End of Program");