Graded problems for programming practice

Problem 1
Write a function called convertToSeconds. Given three ints hours, mins, secs, return an int that is the total number of seconds in time period represented by the arguments.


convertToSeconds(0, 0, 1) → 1 convertToSeconds(1, 0, 0) → 3600 convertToSeconds(1, 2, 3) → 3723

Problem 2
Write a function called stringTimes. Given a string and an int n, return a larger string that is n copies of the original string. Note that the function should return the String, not print it.


stringTimes(“Hi”, 2) → “HiHi”
stringTimes(“Hi”, 3) → “HiHiHi”
stringTimes(“Hi”, 1) → “Hi”

What happens if the function is called with a negative n? Adapt your code to cope with this problem.

Problem 3
n! (pronounced “n factorial”) is defined in mathematics as n x (n-1) x (n-2) x … x 2 x 1. For example 5! = 5 x 4 x 3 x 2 x 1 = 120. Write a function factorial that, given an integer n, returns n!


factorial(2) → 2
factorial(6) → 720
factorial(10) → 3628800

Use your function to print out the factorials of the first 10 numbers. What is the highest factorial that your program can calculate?

Problem 4
Write a function isHeads that will simulate the toss of coin. Use your function to write another function headsInARow that, given an int n, will return the number of coin tosses required before n heads occurred in a row. Use your function to find out the average number of coin tosses required to toss heads five times in a row. (Don’t know how to simulate random events in Java? Google “Java random”.)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s