Table of Contents
Question 6
Implementation in C
Output
Home Backend Development C++ Recursion practice problems and solutions

Recursion practice problems and solutions

Sep 15, 2023 am 10:05 AM
recursion question solution

Recursion practice problems and solutions

In this article, we will discuss some recursion practice problems and their detailed solutions.

Let’s first understand what recursion is and how it works:

Recursion - Recursion is a programming technique in which a function or method calls itself multiple times to solve a problem. This function breaks the problem into smaller sub-problems and solves them until the base case is reached.

The basic case is a stopping condition that ensures that the function stops calling itself and returns the result within a limited time.

Recursion is a powerful technique for solving complex problems, but it is important to design it carefully to avoid infinite loops and to ensure that the function terminates correctly when a function is called recursively multiple times.

Question 1

This is the most basic issue related to recursion.

Find the factorial of a given number using the concept of factorial.

Implementation in C

#include <bits/stdc++.h>
using namespace std;
// recursive function to 
// calculate factorial of number
int Numberfact(int number) {
// base condition
    if(number == 1) {
        return 1;
    } else {
        return number * Numberfact(number-1);
    }
}
// main code
int main() {
   int number = 5;
   cout<< " The factorial of 5 is " << Numberfact(number);
   return 0;
}
Copy after login

Output

The factorial of 5 is 120
Copy after login

Question 2

In this problem, we need to print the n-th number in the sequence starting from 1, where the i-th number is the sum of its first two numbers, commonly known as the Fibonacci sequence.

Implementation in C

#include <bits/stdc++.h>
using namespace std;
// function to 
// calculate nth number of
// Fibonacci series
int Numberfib(int number) {
   // base condition
   if(number <= 1) {
      return number;
   } else {
      return Numberfib(number-1)+Numberfib(number-2);
   }
}
// main code
int main() {
   int number = 9;
   cout<< " The 9th number of the Fibonacci series is " << Numberfib(number);
   return 0;
}
Copy after login

Output

The 9th number of the Fibonacci series is 34
Copy after login

Question 3

Calculate the sum of the digits in a given number

Implementation in C

#include <bits/stdc++.h>
using namespace std;
// recursive method to 
// calculate sum of digits
int Sumofdigits(int number) {
// base case
   if(number <=10) {
      return number;
   }
   else {
      return number%10 + Sumofdigits( number/10 );
   }
}
// main code
int main() {
   int number = 563;
   cout<< " The sum of digits of the number " << number << " is "<< Sumofdigits(number);
   return 0;
}
Copy after login

Output

The sum of digits of the number 563 is 14
Copy after login

Question 4

Calculate the value of a number raised to the "power" power.

In this question, we will be given two numbers "number" and "power", and our task is to find the "power" power of the number "number".

Implementation in C

#include <bits/stdc++.h>
using namespace std;
// recursive method to 
// generate the nth power
// of a given number
int powerofx( int nums , int pow) {
   // termination condition
   if(pow == 0) {
      return 1;
   } else {
      return nums*powerofx(nums, pow-1);
   }
}
// main code
int main() {
   int nums = 2;
   int pow =6;
   cout<< " The number " << nums << " To the power "<< pow <<" is "<< powerofx(nums, pow);
   return 0;
}
Copy after login

Output

The number 2 To the power 6 is 64
Copy after login

Question 5

Find the GCD (greatest common divisor) of two numbers.

GCD stands for Greatest Common Divisor, which is the largest number by which two or more numbers can be divided without a remainder. It is also called the highest common factor (HCF) of these numbers.

Suppose we have two different numbers: 14 and 28.

The factors of 14 are 1, 2, 7 and 14.

The factors of

28 are 1, 2, 4, 7, 14 and 28.

We can then find the common factors of these two numbers, which are 1, 2, 7 and 14. The largest number that can divide both 14 and 28 without leaving a remainder is 14, so the greatest common divisor of 14 and 28 is 14.

Implementation in C

#include <bits/stdc++.h>
using namespace std;
// function to recursively
// calculate the gcd
int greatestcommondivisor(int num1, int num2) {
   if (num2 == 0) {
      return num1;
   } else {
      return greatestcommondivisor(num2, num1 % num2);
   }
}
// main code
int main() {
   int num1 = 36;
   int num2 =60;
   cout<< " The Greatest common divisor of " << num1 << " and "<< num2<<" is "<< greatestcommondivisor(num1, num2);
   return 0;
}
Copy after login

Output

The Greatest common divisor of 36 and 60 is 12
Copy after login

Question 6

Print array in reverse order

We get an array containing n integers, and our task is to print out the same array in order, with the first number as the last number, the second number as the second to last number, and so on.

Implementation in C

#include <bits/stdc++.h>
using namespace std;
// recursive function to 
// =reverse print the given array
void reverseprint(int nums[], int begining, int end) {
   if (begining >= end) {
      return ;
   } else {
      cout << nums[end-1] << " ";
      reverseprint(nums, begining, end - 1);
   }
}
// main code
int main() {
   int size =4;
   int nums[] = { 2, 3, 4, 5 } ;
   cout<< " the given array is reverse order is " << endl ;
   reverseprint(nums, 0, size);
   return 0;
}
Copy after login

Output

the given array is reverse order is 
5 4 3 2 
Copy after login

Here are some more basic practice questions to master a basic level of recursion -

Write a function to recursively check whether a string is a palindrome.

Write a function to find the factorial of a given number using tail recursion.

Write a function to solve the Tower of Hanoi problem.

Write a function to perform a binary search on a sorted array.

The above is the detailed content of Recursion practice problems and solutions. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recursive implementation of C++ functions: Is there a limit to recursion depth? Recursive implementation of C++ functions: Is there a limit to recursion depth? Apr 23, 2024 am 09:30 AM

The recursion depth of C++ functions is limited, and exceeding this limit will result in a stack overflow error. The limit value varies between systems and compilers, but is usually between 1,000 and 10,000. Solutions include: 1. Tail recursion optimization; 2. Tail call; 3. Iterative implementation.

Do C++ lambda expressions support recursion? Do C++ lambda expressions support recursion? Apr 17, 2024 pm 09:06 PM

Yes, C++ Lambda expressions can support recursion by using std::function: Use std::function to capture a reference to a Lambda expression. With a captured reference, a Lambda expression can call itself recursively.

Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Implementing Machine Learning Algorithms in C++: Common Challenges and Solutions Jun 03, 2024 pm 01:25 PM

Common challenges faced by machine learning algorithms in C++ include memory management, multi-threading, performance optimization, and maintainability. Solutions include using smart pointers, modern threading libraries, SIMD instructions and third-party libraries, as well as following coding style guidelines and using automation tools. Practical cases show how to use the Eigen library to implement linear regression algorithms, effectively manage memory and use high-performance matrix operations.

Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Recursive implementation of C++ functions: Comparative analysis of recursive and non-recursive algorithms? Apr 22, 2024 pm 03:18 PM

The recursive algorithm solves structured problems through function self-calling. The advantage is that it is simple and easy to understand, but the disadvantage is that it is less efficient and may cause stack overflow. The non-recursive algorithm avoids recursion by explicitly managing the stack data structure. The advantage is that it is more efficient and avoids the stack. Overflow, the disadvantage is that the code may be more complex. The choice of recursive or non-recursive depends on the problem and the specific constraints of the implementation.

Detailed explanation of C++ function recursion: application of recursion in string processing Detailed explanation of C++ function recursion: application of recursion in string processing Apr 30, 2024 am 10:30 AM

A recursive function is a technique that calls itself repeatedly to solve a problem in string processing. It requires a termination condition to prevent infinite recursion. Recursion is widely used in operations such as string reversal and palindrome checking.

Common causes and solutions for Chinese garbled characters in PHP Common causes and solutions for Chinese garbled characters in PHP Mar 16, 2024 am 11:51 AM

Common causes and solutions for PHP Chinese garbled characters. With the development of the Internet, Chinese websites play an increasingly important role in our lives. However, in PHP development, the problem of Chinese garbled characters is still a common problem that troubles developers. This article will introduce the common causes of Chinese garbled characters in PHP and provide solutions. It also attaches specific code examples for readers' reference. 1. Common reasons: Inconsistent character encoding: Inconsistencies in PHP file encoding, database encoding, HTML page encoding, etc. may lead to Chinese garbled characters. database

Analysis and solutions for why Black Shark mobile phone automatically shuts down and turns on while charging Analysis and solutions for why Black Shark mobile phone automatically shuts down and turns on while charging Mar 24, 2024 pm 02:09 PM

The Black Shark mobile phone is a gaming phone popular among young people. Its excellent performance and unique design have attracted the favor of many players. However, in daily use, some users reported that Black Shark phones automatically shut down when charging or failed to start after being connected to a charger, which caused trouble to users. This article will discuss the problem of automatic shutdown and startup of Black Shark mobile phones from the aspects of cause analysis and solutions to help users better solve this problem. 1. Cause Analysis Charger Quality Issues: Low-quality chargers may cause voltage instability, or

C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application C++ Recursion Advanced: Understanding Tail Recursion Optimization and Its Application Apr 30, 2024 am 10:45 AM

Tail recursion optimization (TRO) improves the efficiency of certain recursive calls. It converts tail-recursive calls into jump instructions and saves the context state in registers instead of on the stack, thereby eliminating extra calls and return operations to the stack and improving algorithm efficiency. Using TRO, we can optimize tail recursive functions (such as factorial calculations). By replacing the tail recursive call with a goto statement, the compiler will convert the goto jump into TRO and optimize the execution of the recursive algorithm.

See all articles