1. Sum of integers The sum of the integers from 1 to n is given by the formula:
sum = n(n + 1)/2
Write a program that inputs a value for n from a text field and calculates the sum two ways – firstly by using the formula and secondly by adding up the numbers using a loop.
2. Interest calculation The program given in the text calculates interest year by year. An alternative is to use a formula for calculating interest. If an amount p is invested at interest rate r for n years, the accumulated value v is:
v = p(1 + r)
n
Write a program that accepts values for p (in dollars), r (as a percentage) and n from text fields and displays the accumulated value in a text field.
Q103
Random numbers Random numbers are often used in computational and simulation programs, called Monte Carlo methods. We have already met the library class Random that enables us to create a random number generator as follows:
Random random = new Random();
Then we call nextInt to obtain an integer random number in the range 0 to 1 as follows:
int number = random.nextInt(2);
Write a program to check out the random number generator. Provide a button that creates a set of 100 random numbers that have the value either 0 or 1. Count the number of values equal to 0 and the number equal to 1. (They should be approximately equal.)