Calculate simple interest table

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
C# Code Snippets

C# Source Code Bank

See also …
edit

This C# code snippet inputs the principal, interest, and duration in years of a simple loan. Then, it calculates simple interest for each year of the loan.

public class CalculateInterestTable
{
   public static void Main (string[] args)
   {
      Console.Write ("Enter principal amount: ");
      decimal principal = 
         Convert.ToDecimal (Console.ReadLine());
      if (principal < 0)
      {  // principal cannot be negative
         Console.WriteLine ("Principal cannot be negative");
         principal = 0;
      }
 
      Console.Write ("Enter interest rate   : ");
      decimal interest = Convert.ToDecimal (Console.ReadLine());
      if (interest < 0)
      {  // interest cannot be negative
         Console.WriteLine ("Interest cannot be negative");
         interest = 0;
      }
 
      Console.Write ("Enter number of years : ");
      int noYears = Convert.ToInt32 (Console.ReadLine());
 
      Console.WriteLine ("\nPrincipal = " + principal 
         + "\nInterest  = " + interest + "%"
         + "\nDuration  = " + noYears + " years\n");
 
      // loop through number of years specified 
      int year = 1;
      while (year <= noYears)
      {
         // calculate interest
         decimal interestPaid = principal * (interest / 100);
 
         // calculate new principal
         principal += interestPaid;
 
         // round to the nearest penny
         principal = decimal.Round (principal, 2);
 
         Console.WriteLine ("Year " + year + " $ " + principal);
         year++;
      }
      Console.WriteLine ("\nPress Enter to stop");
      Console.Read();
   }
}


 Calculate Simple Interest Table (program output)
Enter principal amount: 10000

Enter interest rate  : 20 Enter number of years : 5


Principal = 10000 Interest = 20% Duration = 5 years


Year 1 $ 12000.0 Year 2 $ 14400.00 Year 3 $ 17280.00 Year 4 $ 20736.00 Year 5 $ 24883.20

See also



Personal tools