how to create a series

Hi guys.
I want to calculate the 15th term of series a[1]=2, a[n]=a[n-1]+2
my code doesn't work
#include <cstdlib>
#include <iostream>

using namespace std;
int apple (int);

int main(int argc, char *argv[])
{

cout<<apple(1)<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
int apple (int n)
{
int c=2;
if (n<16)
c= apple(n-1)+2;

cout<<c<<endl;
return c;


}
You should include sentient to avoid infinite loop in your recursive function:
1
2
3
4
5
6
7
int apple(int n)
{
    if (n <= 1)
        return 2;
    else
        return apple(n-1)+2;
} 
Last edited on
but the max number is 15, so i need add somthing more.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstdlib>
using namespace std;
//===============================
int apple(int n){
	int retVal = 2;
	for(int i=0;i<n;++i) retVal += 2;
	return retVal;
}
//===============================
int main(int argc, char *argv[]){
	int n = atoi(argv[1]);
	cout<<'\n'<<apple(n)<<"\n\n";
	return 0;
} 
Topic archived. No new replies allowed.