Solutions to Sample Final Exam QuestionsΒΆ

  1. Write a while-loop that uses the println function to print the numbers from 15 to 188 on the console:

    15
    16
    17
    18
    ...
    187
    188
    

    Solution:

    int i = 15;
    while (i <= 188) {
       println(i);
       ++i;
    }
  2. Suppose age is a variable of type int that has already been defined and given a value (although you don’t know what the value is). Using if-statements, write code that does the following:

    • if age is 0 or less, then print “that’s impossible!”
    • if age is 1 or 2, then print “you’re very young”
    • if age is 3 to 12, then print “Pokemon rocks!”
    • if age is 13 to 19, then print “you’re a teenager”
    • if age is 20 or more, then print “you are incredibly old”

    Your code should print exactly one message.

    Solution:

    if (age <= 0) {
       println("that's impossible!");
    } else if (age == 1 || age == 2) {
       println("you're very young");
    } else if (age >= 3 && age <= 12) {
       println("Pokemon rocks!");
    } else if (age >= 13 && age <= 19) {
       println("you're a teenager");
    } else if (age >= 20) {
       println("you are incredibly old");
    }

Previous topic

Sample Final Exam Questions

Next topic

(Extra) An Exploding Hamburger