chore(CPlusPlus): add recursion programs - part 2 (#574)

pull/582/head
Samruddhi Ghodake 2021-10-15 18:38:10 +05:30 committed by GitHub
parent 228d6e3615
commit f85160e131
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 148 additions and 0 deletions

View File

@ -158,3 +158,6 @@
- [Sum of n natural numbers](Recursion/sum-of-n.cpp)
- [Minimum and maximum element in array](Recursion/min-max-element-in-array.cpp)
- [Prime Check](Recursion/recursive-prime.cpp)
- [Array sorted or not](Recursion\array-sorted-or-not.cpp)
- [Product of two numbers](Recursion\product-of-numbers.cpp)
- [Product of digits in a number](Recursion\product-of-digits.cpp)

View File

@ -0,0 +1,54 @@
/*
Description: A program to check if array is sorted or not using recursion
Approach: To compare last (n-1) element with the second last (n-2) element.
And decrementing the value of n at each recursive call, so that
we can search the entire array.
Time complexity: O(n)
*/
#include <iostream>
using namespace std;
//function starts
bool sorted(int arr[], int n)
{
//base case
if (n == 1 || n == 0)
{
return true;
}
if (arr[n - 1] > arr[n - 2])
{
//recursive function call
return sorted(arr, n - 1);
}
//if the element at (n-1) index is not greater than (n-2) element
//return false directly, which means array is not sorted
return false;
}
//main starts
int main()
{
int arr[] = {8, 2, 3, 4, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
cout << sorted(arr, n);
return 0;
}
/*
Sample Input:
arr=[8, 2, 3, 4, 5, 6]
n=6
Output: 0
Sample Input:
arr=[1,2,3]
n=3
Output: 1
*/

View File

@ -0,0 +1,42 @@
/*
Description: A program to get product of digits using recursion
TIme Complexity: O(n) where n is the number of digits present in the number
*/
#include <iostream>
using namespace std;
//function starts
int dp(int n)
{
//base case
//where n is a one-digit number
if (n % 10 == n)
{
return n;
}
//recursive function call
//at every recursive call, dividing the number by 10
return (n % 10) * dp(n / 10);
}
//main starts
int main()
{
int n = 333;
cout << dp(n);
return 0;
}
/*
Sample Input:
n=333
Output: 27
Sample Input:
n=412
Output: 8
*/

View File

@ -0,0 +1,49 @@
/*
Description: C++ program to find product of 2 numbers using Recursion.
Approach: Product of two numbers (x,y) can be defined as y times sum of x.
Calling the function recursively y times and adding x to it.
Time Complexity: O(n) where n is the value of y
*/
#include <bits/stdc++.h>
using namespace std;
// recursive function to calculate multiplication of two numbers
int product(int x, int y)
{
// if x is less than
// y swap the numbers
if (x < y)
return product(y, x);
// iteratively calculate
// y times sum of x
else if (y != 0)
return (x + product(x, y - 1));
// if any of the two numbers is
// zero return zero
else
return 0;
}
int main()
{
int x = 5, y = 2;
cout << product(x, y);
return 0;
}
/*
Sample Input:
x=5, y=2
Output: 10
Sample Input:
x=6, y=7
Output: 42
*/