SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Recursion
Exercise:
Programming Projects
Question:1 | ISBN:9780132830317 | Edition: 5

Question

A savings account typically accrues savings using compound interest. If you deposit $1,000 with a 10% interest rate per year, then after one year you have a total of $1,100. If you leave this money in the account for another year at 10% interest, then after two years the total will be $1,210. After three years, you would have $1,331, and so on.

Write a program that inputs the amount of money to deposit, an interest rate per year, and the number of years the money will accrue compound interest. Write a recursive function that calculates the amount of money that will be in the savings account using the input information.

To verify your function, the amount should be equal to , where P is the amount initially saved, i is the interest rate per year, and n is the number of years.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

// CompoundInterest.java
import java.util.*;
public class CompoundInterest
{
	public static double calculateAmount(double amount,
			double rate, int years)
	{
		if(years <= 0)
			return amount;
		else
			return calculateAmount(amount * (1 + rate / 100), 
					rate, years - 1);
	}

	public static void main(String[] args)
	{
		Scanner console = new Scanner(System.in);

		System.out.print(
				"Enter the amount of money to deposit: $");
		double P = console.nextDouble();

		System.out.print("Enter an interest rate per year: $");
		double i = console.nextDouble();

		System.out.print("Enter the number of years: ");
		int n = console.nextInt();

		double finalAmount = calculateAmount(P, i, n);

		System.out.printf(
			"\nFinal amount of money in the savings account: $%.2f", finalAmount);
	}
}

Output:

Enter the amount of money to deposit: $1000
Enter an interest rate per year: $10
Enter the number of years: 3

Final amount of money in the savings account: $1331.00
0 0

Discussions

Post the discussion to improve the above solution.