Practice Questions: Week 04


Control Structures

1. Write a program that outputs the numbers from 0 to 10 using a for loop.


2. Write a program that outputs the numbers from 1 to a user specified value, skipping every multiple of 3.


3. Modify your solution to Question 2 so that it counts down instead of up.


4. Write a program that outputs a multiplication table; for example, here is a 5x5 multiplication table:

     1   2   3   4   5
  --------------------
1|   1   2   3   4   5
2|   2   4   6   8  10
3|   3   6   9  12  15
4|   4   8  12  16  20
5|   5  10  15  20  25

5. Exercise 5.14 from the textbook.


6. Exercise 5.17 from the textbook; it's ok if you don't compute the standard deviation.


7. Requires some material from Chapter 6.
The infinite monkey theorem states that a monkey randomly hitting keys on a typewriter keyboard for an infinite amount of time will almost surely reproduce the complete works of William Shakespeare.

Write a Java program that simulates such a monkey. Your program should read in one command line argument that is the target string the monkey is trying to reproduce. Your program should then repeatedly generate random strings of the same length as the target word until the randomly generated string matches the target. You can assume that the word is made up of only the 26 letters of the English alphabet (ignore case). Your program should count the number of randomly generated words needed to match the target. Sample output:

java InfiniteMonkeys Romeo
Took 12399917 attempts to randomly generate ROMEO

Warning: do not try target words longer than 5 or 6 characters in length.

Fun fact: Someone actually tried this experiment with real monkeys. Google "infinite monkey theorem" for the Wikipedia article describing the results.


8. Requires some material from Chapter 6.
Imagine writing out all of the whole numbers starting from 1 concatenated together into a string; for example, the concatenation of the first 15 numbers is:

123456789101112131415

What is the millionth digit in this string? Write a Java program to solve this problem; consider using java.lang.StringBuilder.

From Professor Stewart's Hoard of Mathematical Treasures, Ian Stewart, Basic Books, 2010


9. The number 153 is equal to the sum of the cubes of its digits:

153 = 13 + 53 + 33

Write a program that finds all three-digit numbers with this property (there are a total of four such numbers).

From Professor Stewart's Hoard of Mathematical Treasures, Ian Stewart, Basic Books, 2010