Answers for "how to write a recursive function in c++"

C++
2

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
5

how to make recursive function

// Basic Recursive function
// It works in all languages but lets try with C

// lets make a greedy strlen

int my_recursive_strlen(int index, char *str) // note that index must be set at 0 to work in this case
{
  if (str[index] == '')
    return index + 1;
  else
    return my_recursive_strlen(index++); // i send index + 1 to next function call
  // this increment index in our recursive stack
}

void main(void)
{
  printf("length of Bonjour = %dn", my_recursive_strlen(0, "bonjour"));
}

//output : length of Bonjour = 7

// Recursive functions are greedy and should be used in only special cases who need it
// or who can handle it.

// a function become recursive if she calls herself in stack
Posted by: Guest on August-09-2021
0

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

Code answers related to "how to write a recursive function in c++"

Browse Popular Code Answers by Language