Question 0-1

Suppose a user executes the below run() method.

public static void run() {
    int n = 26;
    int k = 0;
    for(; n != 0; n /= 2) {
        if(n % 2 == 1) {
            k++;
        }
    }
    IO.println(k);
}
Show all the values taken on by the variables of the program.
n
k
What does the method print?

Solution

There were actually three versions of this question. One began with n at 26, one at 22, and one at 20. Here are the answers for these three versions.
n 26 13  6  3  1  0
k  0  1     2  3
In this case, the program would print 3.
n 22 11  5  2  1  0
k  0  1  2     3
In this case, the program would print 3.
n 20 10  5  2  1  0
k  0     1     2
In this case, the program would print 2.

Back to Midterm 0