Discount Each Cash Flow and Sum
In this step, you'll learn how to discount each cash flow and calculate the Net Present Value (NPV) by summing the discounted cash flows in C.
Let's modify the previous npv_calculator.c
file to add NPV calculation:
cd ~/project
nano npv_calculator.c
Replace the previous code with the following implementation:
#include <stdio.h>
#include <math.h>
#define MAX_CASH_FLOWS 10
double calculate_npv(double cash_flows[], int num_cash_flows, double discount_rate) {
double npv = 0.0;
for (int i = 0; i < num_cash_flows; i++) {
// Discount each cash flow: CF / (1 + r)^t
double discounted_cash_flow = cash_flows[i] / pow(1 + discount_rate, i);
npv += discounted_cash_flow;
}
return npv;
}
int main() {
double cash_flows[MAX_CASH_FLOWS];
double discount_rate;
int num_cash_flows;
// Input the number of cash flows
printf("Enter the number of cash flows (max %d): ", MAX_CASH_FLOWS);
scanf("%d", &num_cash_flows);
// Validate number of cash flows
if (num_cash_flows <= 0 || num_cash_flows > MAX_CASH_FLOWS) {
printf("Invalid number of cash flows.\n");
return 1;
}
// Input cash flows
for (int i = 0; i < num_cash_flows; i++) {
printf("Enter cash flow %d: ", i);
scanf("%lf", &cash_flows[i]);
}
// Input discount rate
printf("Enter the discount rate (as a decimal): ");
scanf("%lf", &discount_rate);
// Calculate NPV
double npv = calculate_npv(cash_flows, num_cash_flows, discount_rate);
// Print results
printf("\nInput Summary:\n");
printf("Number of Cash Flows: %d\n", num_cash_flows);
printf("Discount Rate: %.2f%%\n", discount_rate * 100);
printf("\nCash Flows:\n");
for (int i = 0; i < num_cash_flows; i++) {
double discounted_cf = cash_flows[i] / pow(1 + discount_rate, i);
printf("Cash Flow %d: $%.2f (Discounted: $%.2f)\n",
i, cash_flows[i], discounted_cf);
}
printf("\nNet Present Value (NPV): $%.2f\n", npv);
return 0;
}
Compile the program with math library:
gcc -o npv_calculator npv_calculator.c -lm
Run the program to test NPV calculation:
./npv_calculator
Example output:
Enter the number of cash flows (max 10): 3
Enter cash flow 0: -1000
Enter cash flow 1: 500
Enter cash flow 2: 600
Enter the discount rate (as a decimal): 0.1
Input Summary:
Number of Cash Flows: 3
Discount Rate: 10.00%
Cash Flows:
Cash Flow 0: $-1000.00 (Discounted: $-1000.00)
Cash Flow 1: $500.00 (Discounted: $454.55)
Cash Flow 2: $600.00 (Discounted: $495.87)
Net Present Value (NPV): $-49.58
Key points in this implementation:
- Added
calculate_npv()
function to compute NPV
- Used
pow()
function to discount cash flows
- Displayed both original and discounted cash flows
- Calculated and displayed the final NPV
Note: The -lm
flag is used to link the math library for pow()
function.