Home CPSC 220

Final Review



The midterm exam will cover everything we've done thus far. The test will be short answer questions.

It will be cumulative, but will focus on topics since the midterm, especially classes, objects, and recursion.

It mostly will focus on two main areas: reading and understating code, and writing code.

There will also be conceptual questions as well.


Reading Example 1

What does this program output?

public class R1 {
    public static void main(String args[]) {
        int x = 0;

        while (x <= 5) {
            for (int i = x; i > 0; i--) {
                System.out.print(x + " ");



Reading Example 2

Consider the following function "foo":

public static int foo(int x) {
    if (x == 1) {
        return 1;
    else if (x % 2 == 0) {
        return 1 + foo(x / 2);
    } else {
        return 1 + foo(3 * x + 1);

What does foo(10) return?


Reading Example 3

What does the following program print?

public class R3 {
    public static void main(String args[]) {
        int a = 3;
        switch (a) {
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:


Reading Example 4

Consider the following recursive function "bar":

public static void bar(String mesg) {
    if (mesg.equals("")) {


    // subtring(1) finds the string with all but the first character


What does bar("Hello") print?


Writing Example 1: Birthday Paradox

The "birthday paradox" refers to the surprisingly high chances of at least two people in a group sharing a birthday.

We can figure out the probabilities mathematically, or we can simulate the problem. How can we write a program that, given the number of people N, simulates 100 groups of N people with random birthdays, and counts how many groups have a shared birthday?


Writing Example 2: Date Class

If we wanted to improve the previous program by using a nicer representation of dates, we could create a "Date" class that would contain the month and day, and contain functions for comparing two dates, and printing a date to the screen. It should also contain error checking (so that March 40th, and February 31st are not valid dates).

How could we code such a class?


Writing Example 3: Recursion

The following function returns a value from the user between an upper and lower bound:

    // a function which returns an integer from the user
    // between lower and upper bounds, inclusive
    public static int getInput(int lower, int upper) {
        int value;
        Scanner in = new Scanner(System.in);
        do {
            System.out.printf("Enter a value between %d and %d: ", lower, upper);
            value = in.nextInt(); 
        } while (value < lower || value > upper);
        return value;

Could this function be re-written using recursion instead of a loop?

Copyright © 2022 Ian Finlayson | Licensed under a Attribution-NonCommercial 4.0 International License.