I am trying to make a program that calculates the amount of money saved with compound interest. It needs to output the amount of money saved for each year it accrues. This is what i have so far , using a for loop:

int main ()
{
    
	double p;
	double r;
	double n;
	double savings;
	
	cin>>p;
	cin>>r;
	cin>>n;
	
	for(int i=0; i<n; i++)
	{
		savings=p*pow(1.0+r,i);
		cout<<savings<<endl;
		
	}
    return 0;
}

This out puts the amount saved for each year. But now im having trouble changing this to a recursive function to do the same thing. I have something like this but its not working well...Im new to c++ , sorry for any noob code :\

double calculateBalance(double initial, double rate, double term)
{
	int value = initial*pow(1.0+rate,term);
	
	if (term==0) {
		return initial;
	}
	else {
		return calculateBalance(value, rate, term-1);
	}
}

All help would be GREATLY appreciated!!! Thank you!

I believe you kinda made an infinite loop there if I'm not mistaken, because the function isn't really returning a value it's only calling itself over and over, try this I think it will work didn't try it myself.

double calculateBalance(double initial, double rate, double term)
{
	int value = initial*pow(1.0+rate,term);
	
	if (term == 0) 
	{
		return initial;
	}

	else 
	{
		calculateBalance(value, rate, term-1);
	}

	return value;
}

Hope it helps.

Thank you for the response and help. This is the code i have so far and its working well. Because im not as knowledgeable in programming, i was wondering if this is the way it needs to be done. I want to make sure the recursive function is doing all the work. To me, it looks good :) any comments?

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

double calculateBalance(double initial, double rate, double term);

int main ()
{
    
	double p;
	double r;
	double n;
	double savings;
	char answ;
	
	do {
		
	cout<<"Enter the Initial Amount: ";
	cin>>p;
	cout<<"Enter the interest rate: ";
	cin>>r;
	cout<<"Enter the number of years: ";
	cin>>n;
	
	r=(r/100);
	
	cout << "Year" << setw( 21 ) << "Amount on deposit" << endl;
	cout << fixed << setprecision( 2 );
	
		
	for(int i=0; i<=n; i++)
	{
		savings=calculateBalance(p,r,i);
        cout << setw( 4 ) << i << setw( 21 ) << savings << endl;
	}
		cout<<"would you like to calculate another one?: ";
		cin>>answ;
	}
	while(answ=='y');
	
    return 0;
}

double calculateBalance(double initial, double rate, double term)
{
	double value = initial*pow(1.0+rate,term);
	
	if (term==0) {
		return initial;
	}
	else if (term<0) {
		cout<<"Illegal term value";
	}
	else{
		calculateBalance(value, rate, term-1);
	}
	
	return value;
}

Yea that's all there is to it :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.