Recursive
Function
A
function that calls itself is known as recursive function. And, this technique
is known as recursion.
#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;
}
}
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.
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;
}
Enter two positive integers: 350 100
Highest Common Factor (HCF) of 350 & 100 is: 50
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.