|
| 1 | +=== |
| 2 | +Title = To Calculate Compound Interest |
| 3 | +Description = This code takes the principal amount, annual interest rate (as a percentage), |
| 4 | + number of years, and compounding frequency (how many times per year the interest is compounded) |
| 5 | + as input from the user. |
| 6 | + |
| 7 | +##Java Code |
| 8 | + |
| 9 | +import java.util.Scanner; |
| 10 | + |
| 11 | +public class CompoundInterestCalculator { |
| 12 | + public static void main(String[] args) { |
| 13 | + Scanner scanner = new Scanner(System.in); |
| 14 | + |
| 15 | + // Input principal amount |
| 16 | + System.out.print("Enter the principal amount: "); |
| 17 | + double principal = scanner.nextDouble(); |
| 18 | + |
| 19 | + // Input annual interest rate (as a percentage) |
| 20 | + System.out.print("Enter the annual interest rate (as a percentage): "); |
| 21 | + double annualRate = scanner.nextDouble(); |
| 22 | + |
| 23 | + // Input number of years |
| 24 | + System.out.print("Enter the number of years: "); |
| 25 | + int years = scanner.nextInt(); |
| 26 | + |
| 27 | + // Input number of times interest is compounded per year |
| 28 | + System.out.print("Enter the number of times interest is compounded per year: "); |
| 29 | + int compoundingFrequency = scanner.nextInt(); |
| 30 | + |
| 31 | + // Convert annual rate to decimal and calculate compound interest |
| 32 | + double rate = annualRate / 100; |
| 33 | + double amount = principal * Math.pow(1 + (rate / compoundingFrequency), compoundingFrequency * years); |
| 34 | + |
| 35 | + // Calculate compound interest |
| 36 | + double compoundInterest = amount - principal; |
| 37 | + |
| 38 | + // Display the result |
| 39 | + System.out.println("The compound interest after " + years + " years is: " + compoundInterest); |
| 40 | + |
| 41 | + // Close the scanner |
| 42 | + scanner.close(); |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +======= Code Ends Here ======= |
| 47 | + |
| 48 | + |
| 49 | +======= Output 1 ====== |
| 50 | + |
| 51 | +Enter the principal amount: 5000 |
| 52 | +Enter the annual interest rate (as a percentage): 5 |
| 53 | +Enter the number of years: 3 |
| 54 | +Enter the number of times interest is compounded per year: 4 |
| 55 | +The compound interest after 3 years is: 797.1955807499652 |
| 56 | + |
| 57 | + |
| 58 | +======= Output 2 ====== |
| 59 | + |
| 60 | +Enter the principal amount: 10000 |
| 61 | +Enter the annual interest rate (as a percentage): 3.5 |
| 62 | +Enter the number of years: 5 |
| 63 | +Enter the number of times interest is compounded per year: 12 |
| 64 | +The compound interest after 5 years is: 1938.8365362833173 |
| 65 | + |
| 66 | + |
0 commit comments