I am learning c++ recursion give me real application excrises that would be helpfull so…
- User
I am learning c++ recursion give me real application excrises that would be helpfull so that i can understand
- Assistant
I am learning c++ recursion give me real application excrises that would be helpfull so that i can understand
Certainly! Recursion is a powerful tool in C++, enabling you to solve complex problems elegantly by having functions call themselves. Below are some practical exercises that will help you understand how recursion works in real-world applications. Each exercise includes a problem statement, example code signatures, and hints to guide you through the implementation.
Problem: Write a recursive function in C++ that calculates the factorial of a given non-negative integer n.
Function Signature:
unsigned long long factorial(unsigned int n);
Test Cases:
factorial(0) should return 1.factorial(5) should return 120.factorial(10) should return 3628800.Hints:
n is 0 or 1, return 1.n * factorial(n - 1).Problem: Write a recursive function that returns the n-th Fibonacci number.
Function Signature:
unsigned long long fibonacci(unsigned int n);
Test Cases:
fibonacci(0) should return 0.fibonacci(1) should return 1.fibonacci(5) should return 5.fibonacci(10) should return 55.Hints:
n is 0, return 0.n is 1, return 1.fibonacci(n - 1) + fibonacci(n - 2).Note: Be aware that this recursive solution has exponential time complexity. For large n, consider using memoization or an iterative approach.
Problem: Write a recursive function that lists all files in a directory and its subdirectories.
Function Signature:
#include <filesystem>
void listFiles(const std::filesystem::path& directory);
Requirements:
<filesystem> library available in C++17 and later.Hints:
listFiles recursively.std::filesystem::directory_iterator to iterate over directory entries.std::filesystem::is_directory to check if an entry is a subdirectory.Problem: Implement a recursive backtracking algorithm to solve a Sudoku puzzle.
Function Signature:
bool solveSudoku(int grid[9][9]);
Requirements:
grid in place to fill in the solution.true if a solution is found; otherwise, return false.Hints:
0).0 (empty) and try the next number.Problem: Implement the merge sort algorithm using recursion to sort an array of integers.
Function Signature:
void mergeSort(std::vector<int>& arr, int left, int right);
Requirements:
arr in ascending order.Hints:
left >= right, the array is already sorted.int mid = left + (right - left) / 2;mergeSort on the left half (left to mid) and the right half (mid + 1 to right).merge to merge the two sorted halves.Problem: Write a recursive function that prints all permutations of a given string.
Function Signature:
void generatePermutations(std::string str, int left, int right);
Example Usage:
std::string str = "ABC";
generatePermutations(str, 0, str.size() - 1);
Expected Output:
ABC
ACB
BAC
BCA
CBA
CAB
Hints:
left equals right, print the string.left to right and recursively call the function with left + 1.Problem: Implement a recursive algorithm to solve the Knight's Tour problem on a chessboard.
Function Signature:
bool solveKnightsTour(int boardSize);
Requirements:
N x N chessboard without revisiting any square.Hints:
-1.xMove[] and yMove[]).true.Problem: Given a nested list of integers represented as a string (e.g., "[1,[2,[3,4],5],6]"), write a recursive function to parse it and return a flattened list of integers.
Function Signature:
std::vector<int> parseNestedList(const std::string& str);
Requirements:
Hints:
'[', recursively parse the nested list.Problem: Solve the Tower of Hanoi problem using recursion.
Function Signature:
void towerOfHanoi(int n, char fromRod, char toRod, char auxRod);
Example Usage:
int n = 3; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods
Expected Output:
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C
Hints:
n is 1, move the disk from fromRod to toRod and return.n-1 disks from fromRod to auxRod using toRod as auxiliary.toRod.n-1 disks from auxRod to toRod using fromRod as auxiliary.Problem: Implement recursive functions to insert and search for elements in a binary search tree (BST).
Struct Definition:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
Function Signatures:
TreeNode* insert(TreeNode* root, int key);
bool search(TreeNode* root, int key);
Requirements:
true if the key exists in the BST; otherwise, false.Hints:
root is nullptr, create a new TreeNode and return it.key is less than root->val, insert into the left subtree; else, insert into the right subtree.root is nullptr, return false.key equals root->val, return true.Problem: Implement recursive DFS traversal of a graph.
Function Signature:
void DFS(int vertex, std::vector<bool>& visited, const std::vector<std::vector<int>>& adjList);
Requirements:
Hints:
visited[vertex] = true.v of vertex, if visited[v] is false, call DFS(v, visited, adjList).DFS, initialize the visited vector to false for all vertices.Problem: Write a recursive function to generate all subsets (the power set) of a given set of integers.
Function Signature:
void generateSubsets(const std::vector<int>& set, int index, std::vector<int>& current, std::vector<std::vector<int>>& allSubsets);
Requirements:
allSubsets.Hints:
index equals the size of the set, add a copy of current to allSubsets.set[index] to current and recurse with index + 1.current (if included) and recurse with index + 1.Problem: Implement a recursive descent parser for simple arithmetic expressions involving addition, subtraction, multiplication, and division.
Function Signatures:
int parseExpression(const std::string& expr, size_t& index);
Requirements:
"2 + 3 * (4 + 5)" and compute their values.Grammar Simplification:
Expression ::= Term { ('+' | '-') Term }*
Term ::= Factor { ('*' | '/') Factor }*
Factor ::= Number | '(' Expression ')'
Number ::= [0-9]+
Hints:
Term and Factor.std::isdigit for number parsing.index reference carefully to keep track of current parsing position.Problem: Write a recursive function to calculate the total size of a directory, including all its subdirectories and files.
Function Signature:
uintmax_t calculateDirectorySize(const std::filesystem::path& directory);
Requirements:
<filesystem> library (C++17 or later).Hints:
std::filesystem::file_size.std::filesystem::directory_iterator to iterate over directory entries.Problem: Solve the N-Queens problem using recursion and backtracking.
Function Signature:
bool solveNQueens(int n, int row, std::vector<int>& positions);
Requirements:
n queens on an n x n chessboard so that no two queens threaten each other.positions vector holds the column positions of queens for each row.Hints:
row equals n, all queens are placed successfully.Problem: Implement the quick sort algorithm using recursion to sort an array of integers.
Function Signature:
void quickSort(std::vector<int>& arr, int low, int high);
Requirements:
arr in ascending order.partition to rearrange elements.Hints:
low >= high, the array subsection is sorted.quickSort on the subarrays before and after the pivot.Problem: Write a recursive function to compute x raised to the power n.
Function Signature:
double power(double x, int n);
Test Cases:
power(2, 3) should return 8.power(5, 0) should return 1.power(2, -2) should return 0.25.Hints:
n is 0, return 1.n: Return x * power(x, n - 1).n: Return 1 / power(x, -n).Optimization: For better performance, especially with large n, use the exponentiation by squaring method.
Problem: Write a recursive function that calculates the sum of digits of a non-negative integer.
Function Signature:
int sumOfDigits(int n);
Test Cases:
sumOfDigits(123) should return 6.sumOfDigits(0) should return 0.Hints:
n is 0, return 0.(n % 10) + sumOfDigits(n / 10).Problem: Write a recursive function to reverse a string.
Function Signature:
std::string reverseString(const std::string& str);
Test Cases:
reverseString("hello") should return "olleh".reverseString("") should return "".Hints:
reverseString(str.substr(1)) + str[0];Problem: Given the root of a binary tree, flatten the tree into a linked list in-place using preorder traversal.
Struct Definition:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
};
Function Signature:
void flatten(TreeNode* root);
Requirements:
nullptr.Hints:
root is nullptr, return.These exercises cover a variety of practical applications and complexities related to recursion in C++. Working through them will deepen your understanding and help you apply recursion effectively in real-world problems. Remember to:
If you have questions or need further explanations on any of these exercises, feel free to ask!
Not yet included in a published release.