/* This program calculates and displays depreciation tables.
 *
 * Input:  Amount to be depreciated and the number of years
 * Output: A depreciation table
 ******************************************************************/

#include <iostream>              // <<, >>, cout, cin, fixed, showpoint
#include <cassert>               // assert()
#include <iomanip>               // setprecison(), setw()
using namespace std;

int YearSum(int n);
void DisplayTable(int numYears, double amount, double yearSum);

int main()
{
  int numYears;                 // number of years, and
  double amount;                // amount to depreciate

  cout << "This program computes a depreciation tables using\n"
          "the sum-of-the-years'-digits method.\n\n"
          "Enter the number of years over which to depreciate: ";
  cin >> numYears;
  cout << "Enter the amount to be depreciated: ";
  cin >> amount;

  double sum = YearSum(numYears);
  DisplayTable(numYears, amount, sum);
}


/* YearSum(n) computes the sum of the integers from 1 to n.
 *
 *  Receive:      n, an integer
 *  Precondition: n > 0
 *  Return:       The sum 1 + 2 + ... + n
 *********************************************************/

int YearSum(int n)
{
  assert(n > 0);

  int sum = 0;

  for (int count = 1; count <= n; count++)
    sum += count;

  return sum;
}

/* DisplayTable() displays a depreciation table for a given
 * amount over numYears years using the sum-of-the-years'-digits
 * method; yearSum is the sum 1 + 2 + ... + numYears.
 *
 *  Receive: numYears, an integer
 *           amount, a real
 *           yearSum, a real
 *  Output:  A depreciation table
 *  Uses:    setprecision() and setw() from iomanip library
 ****************************************************************/

void DisplayTable(int numYears, double amount, double yearSum)
{
  cout << "\nYear -  Depreciation"
       << "\n--------------------\n";

  double depreciation;

  cout
  << setiosflags(ios::showpoint | ios::fixed)
  << setprecision(2);

  for (int year = 1; year <= numYears; year++)
  {
    depreciation = (numYears - year + 1) * amount / yearSum;
    cout << setw(3) << year
         << setw(13) << depreciation << endl;
  }
}
