how to write a recursive function in c++ code example

Example 1: recursion in c++

//AUTHOR:praveen
//Function calling itself 
//Example in c++
#include<iostream>
using namespace std;
int recursion(int a){
  	if(a==1)//BASE CASE
      return 0;
	cout<<a;
  	a=a-1;
  	return recursion(a);//FUNCTION CALLING ITSELF
}
int main(){
  	int a=5; 
	recursion(a);
  	return 0;
}
//OUTPUT: 5 4 3 2

Example 2: recursion in cpp with reference

void sum_digits(int & n, int & sum)
{
  if ( n == 0 ) return;
  sum += n % 10;
  n /= 10;
  sum_digits(n, sum);
}

#include <iostream>
using namespace std;

int main()
{
  int n, sum=0;
  cout << "enter a non-negative number" << endl;
  cin >> n;
  if ( n < 0 ) return -1; // don't trust the user
  sum_digits(n,sum);
  cout << "sum is " << sum << endl;
}

Tags:

Cpp Example