0% found this document useful (0 votes)
15 views3 pages

Recursion Problem

The document contains C++ implementations of four algorithms: factorial, Fibonacci, binary conversion, and Tower of Hanoi. Each algorithm is defined in a separate function with a main function demonstrating its usage. The code snippets illustrate recursive approaches for solving these problems.

Uploaded by

ubangera.ajay27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Recursion Problem

The document contains C++ implementations of four algorithms: factorial, Fibonacci, binary conversion, and Tower of Hanoi. Each algorithm is defined in a separate function with a main function demonstrating its usage. The code snippets illustrate recursive approaches for solving these problems.

Uploaded by

ubangera.ajay27
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Factorial :

#include <iostream>
long long factorial(int n) {
if (n < 0) {
return -1;
}
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num = 5;
std::cout << "Factorial of " << num << " is " << factorial(num)
<< std::endl;
return 0;
}

Fibonacci
#include <iostream>
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int num = 10;
std::cout << "Fibonacci number at position " << num << " is "
<< fibonacci(num) << std::endl;
return 0;
}

Binary Conversion :
#include <iostream>
void toBinary(int n) {
if (n > 1) {
toBinary(n / 2);
}
std::cout << n % 2;
}
int main() {
int num = 13;
std::cout << "The binary representation of " << num << " is ";
toBinary(num);
std::cout << std::endl;
return 0;
}
Tower of Hanoi :
#include <iostream>
void towerOfHanoi(int n, char from_rod, char to_rod, char
aux_rod) {
if (n == 0) {
return;
}
towerOfHanoi(n - 1, from_rod, aux_rod, to_rod);
std::cout << "Move disk " << n << " from rod " << from_rod
<< " to rod " << to_rod << std::endl;
towerOfHanoi(n - 1, aux_rod, to_rod, from_rod);
}
int main() {
int num_disks = 3;
std::cout << "Tower of Hanoi with " << num_disks << "
disks:" << std::endl;
towerOfHanoi(num_disks, 'A', 'C', 'B');
return 0;
}

You might also like