Colorado State University

Recitation R9 - Control Loops
Spring 2015

CS160: Foundations in Programming


The goal of this lab is to:

Understanding for, while and do-while loops

WITHOUT RUNNING THIS CODE, answer the following questions on paper or in a file:

Question 1) What does the following loop output?
for(int i = 1; i < 12; i+=2)
    System.out.println(i);
Question 2) What does the following loop output?
int j = 0;
while (j <= 8) {
    System.out.println(++j);
}
Question 3) What does the following loop output?
for(int j = 7; j >= 0; j--);
    System.out.print(j + " ");
    // are you sure?
Question 4) What does the following loop output?
for(int n = 0; n > 0; n++)
    System.out.println(n);

Question 5) What does the following loop output?
int j = 0;
do {
    System.out.println(j);
    j--;
}
while (j > 0);


Today's assignment: Writing simple loops

Complete the following tasks and submit to Checkin on the course website when you are finished.

  1. Create a new project in Eclipse called R9, and a new class called R9.java.
  2. Cut and paste the following code inside the curly braces for R9:
    public static void reverseString(String s) {
        // add code here
    }
    
    public static void printAscii(char start, char end) {
        // add code here
    }
    
    public static int computeFactorial(int num) {
        // add code here
    }
    
    public static void areWeThereYet(Scanner keyboard) {
        // add code here
    }
    
  3. Complete reverseString(): using a for loop, print out all characters of of the String parameter in reverse order. All characters should print on one line, and the method should end by printing a newline.
  4. Complete printAscii(): using a for loop, print out all characters in the ascii table between the codes: start and end (inclusive). The method should print everything on one line, ending with a newline.
  5. Complete computeFactorial(): using a while loop, compute and return the factorial of the integer parameter. The factorial of 0 is 1, and you do not need to handle negative numbers.
  6. Complete areWeThereYet(): using a do-while loop, print "Are we there yet? " until the user types in "yes", with any combination of uppercase or lowercase letters. When a "yes" is input, print "Finally!" followed by a newline and return. Use the Scanner parameter, keyboard to read input from the user. Assume the user only types in single words.
  7. Test your methods by calling them in the main method. To test areWeThereYet(), you'll have to create an object of type Scanner in the main method.

You must submit your R9.java program using the Checkin tab on the course website, automated grading will be enabled.


© 2015 CS160 Colorado State University. All Rights Reserved.