Recursion and Non Recursion Programs
Recursion and Non Recursion Programs
Aim
To write a C++ Program to implement Recursive and Non recursive algorithms
Recursive Algorithms
1. Factorial of a given Number using Recursion
2. Fibonacci using Recursion
3. Tower of Hanoi
4. Binary Digits
5. Binary Search
Non-Recursive Algorithms
1. GCD
2. Sequential Search
3. Maximum Element
4. Fibonacci Series
5. Unique Element
6. Matrix Multiplication
7. Binary Search
8. Binary Digits
9. Brute force string matching
Aim
To write a C++ Program to implement Factorial of a given Number using Recursion.
Algorithm
Step1:
Start with a positive integer n.
Step 2:
If n is 0 or 1, return 1 (the base case).
Step 3:
Otherwise, recursively calculate the factorial of n-1.
Step 4:
Multiply the result from step 3 by n.
Step 5:
Return the result as the factorial of n.
Program
#include <iostream>
using namespace std;
unsigned long long factorial(int n)
{
if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}
int main()
{
int n;
cin >> n;
if (n < 0)
{
cout << "Factorial is not defined for negative numbers." << std::endl;
}
else
{
unsigned long long result = factorial(n);
cout << "Factorial of " << n << " is " << result << std::endl;
}
return 0;
}
Sample Input: Sample Output:
5 The factorial of 5 is 120
Aim
To write a C++ Program to implement nth Fibonacci term using Recursion.
Algorithm
Step 1:
Create an array fib of size n+1 to store Fibonacci numbers.
Step 2:
Initialize fib[0] to 0 and fib[1] to 1 because the Fibonacci numbers for 0 and 1 are
known.
Step 3:
For i from 2 to n, do the following:
Step 4:
Set fib[i] to fib[i-1] + fib[i-2].
Step 5:
This step calculates and stores the Fibonacci numbers iteratively, avoiding redundant
calculations.
Step 6:
The fib[n] value now holds the nth Fibonacci number
Program
#include<iostream>
using namespace std;
int fib(int n)
{
if(n<=1)
{
return n;
}
else
{
return fib(n-1) + fib(n-2);
}
}
int main()
{
int n;
cin>>n;
cout<<fib(n);
return 0;
}
Sample Input: Sample Output:
5 3
Aim
To write a C++ program of Tower of Hanoi using Recursion
Algorithm
Step 1:
If there is only one disk to move, simply move it from the source peg to the destination
peg.
Step 2:
Otherwise, follow these steps
Move the top n-1 disks from the source peg to the auxiliary peg using the destination
peg as temporary storage.
Step 3:
Move the largest disk from the source peg to the destination peg.
Step 4:
Move the n-1 disks from the auxiliary peg to the destination peg using the source peg as
temporary storage.
Program
#include <iostream>
using namespace std;
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
if (n == 1) {
cout << "Move disk 1 from " << source << " to " << destination << std::endl;
return;
}
towerOfHanoi(n - 1, source, destination, auxiliary);
cout << "Move disk " << n << " from " << source << " to " << destination << std::endl;
towerOfHanoi(n - 1, auxiliary, source, destination);
}
int main() {
int numDisks;
cin >> numDisks;
if (numDisks <= 0) {
cout << "Number of disks must be greater than zero." << std::endl;
} else {
towerOfHanoi(numDisks, 'A', 'B', 'C');
}
return 0;
}
a. Recursively call decimalToBinary with the integer division of the decimal number by 2
b. Append the remainder of the division (0 or 1) to the result of the recursive call.
Step 5:
The result of the recursive calls will be a binary representation of the decimal number in
reverse order.
Step 6:
Reverse the binary representation obtained from the recursive calls to get the correct
binary representation.
Step 7
Return the binary representation as a string.
Program
#include <iostream>
using namespace std;
int main() {
int decimalNumber;
cin >> decimalNumber;
if (decimalNumber == 0) {
cout << "Binary representation: 0";
} else {
cout << "Binary representation: ";
decimalToBinary(decimalNumber);
}
return 0;
}
Aim
To write a C++ program to implement Binary Search using Recursion
Algorithm
Step 1:
Start with the entire sorted array.
Step 2:
Initialize two pointers, start and end, to the first and last indices of the array,
respectively.
Step 3:
Repeat the following steps until start is less than or equal to end:
Step 4:
Calculate the middle index mid as (start + end) / 2.
Step 5:
If the element at mid is equal to the key, return mid as the index where the key was
found.
Step 6:
If the element at mid is less than the key, update start to mid + 1 to search in the right
half of the array.
Step 7:
If the element at mid is greater than the key, update end to mid - 1 to search in the left
half of the array.
Step 8:
If the loop terminates and the key is not found, return -1 to indicate that the key is not in
the array.
Program
#include<iostream>
using namespace std;
int binsearch(int ar[],int s, int e,int key)
{
if(s<=e)
{
int mid=s + (e-s)/2;
if(ar[mid]==key)
{
return mid;
}
else if(ar[mid]<key)
{
return binsearch(ar,mid+1,e,key);
}
return binsearch(ar,s,mid-1,key);
}
return -1;
}
int main()
{
int num;
cin>>num;
int array[num];
for(int i=0;i<num;i++)
{
cin>>array[i];
}
int key;
cin>>key;
int ans=binsearch(array,0,num-1,key);
// cout<<ans;
if(ans!=-1 && ans<num)
{
cout<<"Key found";
}
else
{
cout<<"Key not found";
}
}
Sample Input: Sample Output:
5 Key Found
12345
5
Aim:
To Find GCD of two numbers without using recursion.
Algorithm:
Step 1:
Read two input integers, a and b, where a >= b.
Step 2:
While b is not equal to 0, repeat the following steps:
Once the loop terminates, a will hold the GCD of the original two numbers.
Step 4:
Return the value of a as the GCD.
Program:
#include <iostream>
using namespace std;
cout << "GCD(" << num1 << ", " << num2 << ") = " << gcd << endl;
return 0;
}
Sample Input: Sample Output:
12 6 GCD(12, 6) = 6
Aim:
To Find whether the element is present or not using Sequential Search.
Algorithm:
Step 1:
Read the size of the array as size.
Step 2:
Declare an integer array array of size size to store the elements of the array.
Step 3:
Read size integers and store them in the array.
Step 4:
Read the integer no that you want to search for in the array.
Step 5:
Implement the search function as follows:
Step 5.1:
Initialize a loop variable i to 0.
Step 5.2:
Iterate through the elements of the array using a for loop from index 0 to size-1.
Step 5.3:
In each iteration, check if the current element (array[i]) is equal to no.
Step 5.4:
If a match is found (array[i] == no), print "Yes" to indicate that the number was found and return
from the function.
Step 5.5:
If the loop completes without finding a match, print "No" to indicate that the number was not
found.
Step 6:
In the main function, call the search function with the array, size, and no.
Program:
#include<iostream>
using namespace std;
void search(int a[],int no,int find)
{
for(int i=0;i<no;i++)
{
if(find==a[i])
{
cout<<"Yes";
return;
}
}
cout<<"No";
}
int main()
{
int size;
cin>>size;
int array[size];
for(int i=0;i<size;i++)
{
cin>>array[i];
}
int no;
cin>>no;
search(array,size,no);
}
Sample Input: Sample Output:
5 Yes
12345
4
Aim:
To Find the maximum element in a array.
Algorithm:
Step 1:
Read the size of the array as size.
Step 2:
Declare an integer array array of size size to store the elements of the array.
Step 3:
Read size integers and store them in the array.
Step 4:
Initialize a variable maxElement with the first element of the array (array[0]) as the initial
maximum.
Step 5:
Iterate through the elements of the array using a for loop from index 1 to size-1.
Step 5.1:
In each iteration, compare the current element (array[i]) with the current maximum
(maxElement).
Step 5.2:
If the current element is greater than the current maximum, update maxElement to be the
current element.
Step 6:
After the loop, maxElement will hold the maximum element found in the array.
Step 7:
Print the value of maxElement as the maximum element in the array.
Program:
#include <iostream>
using namespace std;
int main() {
int size;
cin >> size;
int array[size];
for (int i = 0; i < size; i++) {
cin >> array[i];
}
Step 2:
Initialize two variables, first and second, to 0 and 1, respectively. These variables represent the
first two terms of the Fibonacci series.
Step 3:
Print the message "Fibonacci Series up to n terms: " (where n is the number of terms).
Step 4:
If n is greater than or equal to 1, print the value of first followed by a space.
Step 5:
If n is greater than or equal to 2, print the value of second followed by a space.
Step 6:
Start a loop from i = 3 to i = n:
Step 6.1:
Calculate the next Fibonacci number as next = first + second.
Step 6.2:
Print the value of next followed by a space.
Step 6.3:
Update first to the value of second.
Step 6.4:
Update second to the value of next.
Step 7:
End the loop.
Step 8:
Print a newline to complete the output.
Program:
#include <iostream>
using namespace std;
void generateFibonacci(int n) {
if (n <= 0) {
cout << "Invalid input. Please enter a positive integer." << endl;
return;
}
if (n >= 1) {
cout << first << " ";
}
if (n >= 2) {
cout << second << " ";
}
first = second;
second = next;
}
int main() {
int n;
cin >> n;
generateFibonacci(n);
return 0;
}
Sample Input: Sample Output:
10 0 1 1 2 3 5 8 13 21 34
Aim:
To find Unique Elements in array.
Algorithm:
Step 1:
Read the size of the array as size.
Step 2:
Declare an integer array array of size size to store the elements of the array.
Step 3:
Read size integers and store them in the array.
Step 4:
Initialize an empty hash set (unordered_set) called uniqueElements to keep track of unique
elements.
Step 5:
Print "Unique elements in the array: " to indicate the start of the output.
Step 6:
Iterate through the elements of the array using a loop from index 0 to size-1:
Step 6.1:
Check if the current element (array[i]) is not present in the uniqueElements set.
Step 6.2:
If it's not in the set, insert the element into uniqueElements and print it as a unique element.
Step 7:
End the loop.
Step 8:
Print a newline to complete the output.
Program:
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
int size;
cin >> size;
int array[size];
for (int i = 0; i < size; i++) {
cin >> array[i];
}
findUniqueElements(array, size);
return 0;
}
Sample Input: Sample Output:
10 1234567
1234567123
Aim:
To find a matrix multiplication withour using recursion.
Algorithm:
Step 1:
Read the dimensions of the first matrix:
Input the number of rows, rows1.
Input the number of columns, cols1.
Step 2:
Read the dimensions of the second matrix:
Input the number of rows, rows2.
Input the number of columns, cols2.
Step 3:
Check if matrix multiplication is possible:
If cols1 is not equal to rows2, display an error message and exit the program because matrix
multiplication is not possible.
Step 4:
Initialize three matrices:
Declare a matrix matrix1[rows1][cols1] for the first matrix.
Declare a matrix matrix2[rows2][cols2] for the second matrix.
Declare a matrix result[rows1][cols2] for storing the result of multiplication.
Step 5:
Input elements for the first matrix:
Use nested loops to input and store elements in matrix1.
Step 6:
Input elements for the second matrix:
Use nested loops to input and store elements in matrix2.
Step 7:
Perform matrix multiplication using nested loops:
Iterate through rows of the first matrix (index i from 0 to rows1-1).
Inside the row loop, iterate through columns of the second matrix (index j from 0 to cols2-1).
Initialize result[i][j] to 0.
For each element in the row of the first matrix, iterate through the elements in the
corresponding column of the second matrix (index k from 0 to cols1-1).
Calculate and accumulate result[i][j] as the sum of products of elements from the first and
second matrices: result[i][j] += matrix1[i][k] * matrix2[k][j].
Step 8:
Display the resultant matrix:
Iterate through rows of the result matrix (index i from 0 to rows1-1).
Inside the row loop, iterate through columns of the result matrix (index j from 0 to cols2-1).
Print each element in the result matrix.
Step 9:
End the program.
Program:
#include <iostream>
using namespace std;
int main() {
int rows1, cols1, rows2, cols2;
cin >> rows1;
cin >> cols1;
cin >> rows2;
cin >> cols2;
if (cols1 != rows2) {
cout << "Matrix multiplication is not possible. Column count of the first matrix must be
equal to the row count of the second matrix." << endl;
return 1;
}
int matrix1[rows1][cols1], matrix2[rows2][cols2], result[rows1][cols2];
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
cin >> matrix1[i][j];
}
}
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
cin >> matrix2[i][j];
}
}
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return 0;
}
Aim:
To search an element by binary search method without using recursion
Algorithm:
Step 1:
Initialize variables:
While low is less than or equal to high, repeat the following steps:
Step 2.1:
Calculate the middle index mid as (low + high) / 2.
Step 2.2:
Check if the element at array[mid] is equal to the target element:
- If it is equal, set ans to mid and break out of the loop.
Step 2.3:
If the element at array[mid] is less than element, update low to mid + 1 to search in the
right half of the array.
Step 2.4:
If the element at array[mid] is greater than element, update high to mid - 1 to search in
the left half of the array.
Step 3:
After the while loop:
Aim:
To convert decimal number into binary number without using recursion.
Algorithm:
Step 1:
Read the decimal number to be converted and store it in a variable, decimal.
Step 2:
Initialize an empty stack (a data structure) called binaryDigits to store the binary digits.
Step 3:
Check if decimal is equal to 0:
If decimal is 0, push the value 0 onto the binaryDigits stack and skip to Step 7.
Step 4:
Enter a loop that continues until decimal is greater than 0:
Step 6:
Update decimal by performing integer division by 2 (i.e., decimal = decimal / 2).
Step 7:
Print "Binary representation: " to indicate the start of the output.
Step 8:
Enter a loop that continues until the binaryDigits stack is empty:
Pop the top element from the binaryDigits stack and print it.
Step 9:
End the program.
Program:
#include <iostream>
#include <stack>
using namespace std;
int main() {
int decimal;
cin >> decimal;
decimalToBinary(decimal);
return 0;
}
Sample Input: Sample Output:
7 111
Aim:
To execute Brute force string matching without using recursion.
Algorithm:
Step 1:
Read the text string and pattern string.
Step 2:
Get the lengths of the text string and pattern string:
Step 3.2:
Enter a loop that checks character by character if the pattern matches the text string:
- For each position j in the pattern string, do the following:
Step 3.3:
If the inner loop completes (i.e., j reaches patternLength), print "Pattern found at index
i."
#include <iostream>
#include <string>
using namespace std;
int main() {
string text, pattern;
getline(cin, text);
getline(cin, pattern);
bruteForceStringMatch(text, pattern);
return 0;
}
Sample Input: Sample Output:
ababcababcabc Pattern found at index 0
Abc Pattern found at index 5
Pattern found at index 8
Pattern found at index 11