Learn recursion , simple problem recursion c++

What is recursion?

Recursion in coding is like a mirror reflecting itself. It’s a technique where a function calls itself to solve a smaller instance of the same problem. It’s like breaking a big problem into smaller, more manageable pieces until they’re easy to solve. This process keeps repeating until the smallest, simplest problem is reached, and then the solutions are combined to solve the original problem. Recursion is elegant but requires caution to avoid infinite loops.

What is the difference between recursion and loops

Recursion and loops are both tools used in coding, but they work differently. Loops are like a looping roller coaster; they repeat a set of instructions until a condition is met or for a specified number of times. They’re great for tasks that need repetition without necessarily dividing the problem into smaller parts.

On the other hand, recursion is more like a hall of mirrors; it’s a technique where a function calls itself to solve smaller instances of the same problem. It’s ideal for tackling complex problems by breaking them down into simpler, more manageable parts.

In summary, loops are about repetition, while recursion is about breaking down problems into smaller pieces and solving them recursively. Both have their strengths and are useful depending on the problem at hand.

C++ recursion problems with solutions

1. Calculate the factorial of a number using recursion in C++

#include <iostream>
using namespace std;
int factorial(int num);
int main()
{
	int num;
	cout<<"Enter a num: "<<endl;
	cin>>num;
	cout<<factorial(num);
}
int factorial(int num)
{
	if(num==1)
	{
		return 1;
	}
	else
	{
		return num * factorial(num-1);
	}
}

2. C++ Program to Print the Fibonacci sequence

#include <iostream>
using namespace std;

int fibonacci(int num) {
    if (num == 0)
        return 0;
    else if (num == 1)
        return 1;
    else
        return fibonacci(num - 1) + fibonacci(num - 2);
}

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    cout << endl;
    for (int i = 0; i < num; i++) {
        cout << fibonacci(i) << " ";
    }
    cout << endl;
    return 0;
}

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *