c++ recursion code example
Example 1: recursion in cpp with reference
#include <iostream>
#include <cstdlib>
using namespace std;
int sumDigits(int &);
int main()
{
int n;
sumDigits(n);
}
int sumDigits(int &n)
{
cout << "Enter a non-negative integer: ";
cin >> n;
if (n == 1)
{
return 1;
}
else
{
return (n - 1) + n;
}
cout << "The sum of all digits "<< n << " is: " << n << endl;
system ("PAUSE");
return 0;
}
Example 2: recursion in c++
#include<iostream>
using namespace std;
int recursion(int a){
if(a==1)
return 0;
cout<<a;
a=a-1;
return recursion(a);
}
int main(){
int a=5;
recursion(a);
return 0;
}
Example 3: 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;
sum_digits(n,sum);
cout << "sum is " << sum << endl;
}
Example 4: recursion in c++
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int factorialfun(int num)
{
if (num>0)
{
return num*factorialfun(num-1);
}
else
{
return 1;
}
}
int main()
{
int num;
cin>>num;
cout<<factorialfun(num);
}