9:40 Quiz 0

Statistics:

mean     23.677 (734.000/31)
stddev   4.358
median   24.000
midrange 20.750-27.250

# avg
1 8.77 / 10
2 7.87 / 10
3 7.03 / 10

Question 0-1

Suppose a user executes the following run() method and types the numbers 5 and 22.

public static void run() {
    int a = IO.readInt();
    int b = IO.readInt();

    int m = 0;
    int n = b;
    while(m < n) {
        m += a;
        n -= a;
    }

    IO.println(m - n);
}
Show all the values taken on by the variables of the program.
a
b
m
n
What does the method print?

Question 0-2

Say we've defined the following method.

public static int f(int n) {
    IO.print(n);
    return 1 + n;
}
Suppose our program executes the line
IO.println(1 + f(2 + f(3)));
What is printed in executing this line?

Question 0-3

Fill in run() so that, when executed, the method will compute the factorial of a number the user types. A user executing the method should see the following, for example. (Boldface indicates what the user types.)

Number: 4
24
Recall that n factorial is the product of the integers up to n; for example, the factorial of 4 is 1*2*3*4 = 24.
import csbsju.cs160.*;

public class FindFactorial {
    public static void run() {



    }
}

Solutions

Solution 0-1

a  5
b 22
m  0  5 10 15
n 22 17 12  7
The method will print ``8.''

Solution 0-2

3
6
8

Solution 0-3

import csbsju.cs160.*;

public class FindFactorial {
    public static void run() {
        IO.print("Number: ");
        int num = IO.readInt();
        int fact = 1;
        while(num > 0) {
            fact *= num;
            num--;
        }
        IO.println(fact);
    }
}