Programming Examples
Java program to calculate compound interest
Write a Java program to calculate compound interest using the formula:
where:
- A is the amount of money accumulated after n years, including interest.
- P is the principal amount (the initial amount of money).
- r is the annual interest rate (decimal).
- n is the number of times that interest is compounded per unit year.
- t is the time the money is invested for in year
Solution
import java.util.Scanner;
public class CompoundInterest
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the principal amount (P): ");
double principal = sc.nextDouble();
System.out.print("Enter the annual interest rate (r) in percentage: ");
double annualRate = sc.nextDouble();
System.out.print("Enter the number of times interest is compounded per year (n): ");
int compounded = sc.nextInt();
System.out.print("Enter the time in years (t): ");
int years = sc.nextInt();
double rate = annualRate / 100;
double amount = principal * Math.pow(1 + (rate / compounded), compounded * years);
System.out.println("The amount of money accumulated after " + years + " years, including interest, is: " + amount);
}
}
Output