Answers for "recursion in c++"

C++
1

recursion in cpp with reference

#include <iostream>
#include <cstdlib> //had to force it becasue my compiler (Code::Blocks) does not contain system.

using namespace std;
/*int n = 1, sum = 0;

int sumDigits(int n, int sum)
{
    //
	if (n == 0)
    {
        return sum;
    }
    else
    {
        // applying recursion and returning the value into the function
        sum = sum + n%10;
		n= n/10;
        return sumDigits(n, sum);
    }
}

int main(int argc, char* argv[])
{
	n = 1, sum = 0;

        cout << "Enter a non-negative integer: ";
        cin >> n;
        sum = sumDigits (n, sum);
        cout << "The sum of all digits "<< n << " is: " << sum << endl;

	system ("PAUSE");

        return 0;
}
*/

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;
}
Posted by: Guest on July-01-2020
1

recursion in c++

//recursion in c++
//factorial
#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);
}
Posted by: Guest on April-18-2021
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
Posted by: Guest on September-15-2020

Browse Popular Code Answers by Language