Home | | Computer Science 11th std | C++: Recursive Function

Example C++ Program - C++: Recursive Function | 11th Computer Science : Chapter 11 : Functions

Chapter: 11th Computer Science : Chapter 11 : Functions

C++: Recursive Function

A function that calls itself is known as recursive function. And, this technique is known as recursion.

Recursive Function

 

A function that calls itself is known as recursive function. And, this technique is known as recursion.

 

Example 1: Factorial of a Number Using Recursion

Program 11.26

#include <iostream>

using namespace std;

int factorial(int); // Function prototype //

int main()

{

      int no;

      cout<<"\nEnter a number to find its factorial: ";

      cin >> no;

      cout << "\nFactorial of Number " << no <<" = " << factorial(no);

 return 0;

}

int factorial(int m)

{

      if (m > 1)

      {

      return m*factorial(m-1);

      }

      else

      {

      return 1;

}

 

}

Output :

Enter a number to find its factorial: 5

Factorial of Number 5 = 120

 

Note: Function prototype is mandatory since the function factorial() is given after the main() function.

 

Example 2: Finding HCF of any to number using Recursion

Program 11.27

#include <iostream>

using namespace std;

//Function to find HCF //

int hcf(int n1, int n2)

{

      if (n2 != 0)

      return hcf(n2, n1 % n2);

      else

      return n1;

}

int main()

{

      int num1, num2;

      cout << "Enter two positive integers: ";

      cin >> num1 >> num2;

      cout << "Highest Common Factor (HCF) of " << num1;

      cout<< " & " << num2 << " is: " << hcf(num1, num2); return 0;

}

Output:

Enter two positive integers: 350 100

Highest Common Factor (HCF) of 350 & 100 is: 50

 

Tags : Example C++ Program , 11th Computer Science : Chapter 11 : Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 11 : Functions : C++: Recursive Function | Example C++ Program


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.