This month’s Exercise is one of those old, programming warhorses: Calculate a depreciation schedule. At the simplest level, the solution is a mathematical loop and keeps subtracting a given percentage from a value.
My no-brainer solution is shown at the bottom of this post. Most of the code collects the input and generates the text output. The core of the depreciation process is a for loop:
for(y=0;y<=years;y++) { printf("Year %2d: $%.2f\n",y,cost); cost = cost - (cost * depreciation); }
years
is an int variable representing the number of years to depreciate; cost
and depreciation
are float variables representing the initial cost and the percentage to depreciate, respectively.
The for loop starts with the current year, “year zero,” which is why the loop’s termination condition is <=
and not just <
. For each year, the cost is reduced by the current value minus the percentage of depreciation.
Here’s the full code:
#include <stdio.h> int main() { float cost,depreciation; int years,y; printf("Enter initial cost: $"); scanf("%f",&cost); printf("Enter annual depreciation as a decimal: "); scanf("%f",&depreciation); printf("Enter years to depreciate: "); scanf("%d",&years); puts("\nDepreciation Schedule"); puts("====================="); for(y=0;y<=years;y++) { printf("Year %2d: $%.2f\n",y,cost); cost = cost - (cost * depreciation); } return(0); }
As always, other solutions are possible. The big difference between this code and others is most likely with the output, which could get really fancy. Another option would be to hone the input statements, for example, to allow dollar amounts to be typed with $ , and . characters or to allow the percentage to be input as a string such as 10%. These modifications would require specific input functions, which I’ve demonstrated in other Lessons and Exercises.