Question 0-3

Fill in the below method so that, when executed, it reads an integer n from the user and displays the positive even integers that are less than or equal to n, in ascending order. Following is a sample transcript illustrating how an execution of the method should appear.

Number? 8
2
4
6
8
public static void run() {



}

Solution

There were two versions of the question. One asked for the even integers, and one for the odd integers.
public static void run() {
    IO.print("Number? ");
    int num = IO.readInt();
    for(int i = 2; i <= num; i += 2) {
        IO.println(i);
    }
}
The odd-integer answer is identical, except that it begins i at 1.
    for(int i = 1; i <= num; i += 2) {

Back to Midterm 0