Arithmetic Progression Using recursion C++

I wrote c++ code which gets first character of progression (a1) difference (b) and size of progression (n)from user and my code must print arithmetic progression
but i keep getting "exit status -1". please help me :) i'm noob.
(sorry for bad english)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//Find Arithmetic progression
#include<iostream>
#include<algorithm>
using namespace std;

int arth(int a1, int b, int n)
{
  if (n >= 1)
  {
    return arth(a1 + b, b, n--);
  }
  else 
  {
    return 1;
  }
}

int main()
{
  int a1;
  int b;
  int n;

  cout << "Enter a1: ";
  cin >> a1;

  cout << "Enter b: ";
  cin >> b;

  cout << "Enter n: ";
  cin >> n;

  cout << arth(a1, b, n);
  return 0;
}
--n rather than n--, or you will go on for ever.

You should print your output (cout << a1 << endl;) at the start of arth(), not in main().
Hi nick372060,

If you simplify your program you get this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>

using namespace std;

int arth(int n)
{
	
	if (n > 0)
  	{
  	  //return arth(n = n-1);
          return arth(--n);
  	}
  	else 
  	{
  	  return 1;
  	}
}

int main()
{
  int n;

  cout << "Enter n: ";
  cin >> n;

  cout << arth(n);
  
  return 0;
}


_You don't need to include algorithm
_you don't do anything with the variables a1 and b in your arth() function, so why use them?
_when you call arth() within itself, your program crashed because you're passing a rvalue as a function parameter: n--. You need to make that a Lvalue, so either return (--n) or return (n = n - 1).

Are you aware that all your function is, is a loop which decrements the value of n, until it is equal to 0, and then returns 1? If it is what you wanted to do, then it works.
Last edited on
At line 10, n-- evaluates to the current value of n and decrements n. As a result, you're calling arth() with the same value of n each time. That results in infinite recursion.

To fix this, just change n-- to n-1. You don't need to change the value current call's value of n, you just need to pass the smaller value to the next call.

That will get the code to return, but it will always return 1. To fix this, I think line 14 should return a1 instead of 1.
Thank you all my program is finally working :)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;

void arth( int a, int b, int n )
{
   cout << a << ' ';
   if ( n > 1 ) arth( a + b, b, n - 1 );
}

int main()
{
  int a, b, n;
  cout << "Enter a, b, n: ";
  cin >> a >> b >> n;
  arth( a, b, n );
}


Enter a, b, n: 5 3 6
5 8 11 14 17 20  
Topic archived. No new replies allowed.