0% found this document useful (0 votes)
21 views

Recursion and Non Recursion Programs

Nil

Uploaded by

wasimrajaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Recursion and Non Recursion Programs

Nil

Uploaded by

wasimrajaa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

RECURSION AND NON RECURSION

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;
}

Sample Input: Sample Output:


3 Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Aim
To write a C++ program to implement Binary Digits using Recursion
Algorithm
Step 1:
Create a recursive function, let's call it decimalToBinary, that takes a decimal number as
input.
Step 2:
In the decimalToBinary function, check if the input decimal number is greater than 0.
Step 3:
If the decimal number is 0, return an empty string (base case).
Step 4:
If the decimal number is greater than 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;

void decimalToBinary(int decimalNumber) {


if (decimalNumber > 0) {
decimalToBinary(decimalNumber / 2);
cout << decimalNumber % 2;
}
}

int main() {
int decimalNumber;
cin >> decimalNumber;

if (decimalNumber == 0) {
cout << "Binary representation: 0";
} else {
cout << "Binary representation: ";
decimalToBinary(decimalNumber);
}

cout << endl;

return 0;
}

Sample Input: Sample Output:


7 Binary Representation: 111

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:

a. Calculate the remainder of a divided by b, denoted as r (i.e., r = a % b).

b. Set a to the value of b, and b to the value of r.


Step 3:

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;

int findGCD(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
int main() {
int num1, num2;

cin >> num1 >> num2;

int gcd = findGCD(num1, num2);

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 findMax(int arr[], int size) {

int maxElement = arr[0];

for (int i = 1; i < size; i++) {


if (arr[i] > maxElement) {
maxElement = arr[i];
}
}
return maxElement;
}

int main() {
int size;
cin >> size;
int array[size];
for (int i = 0; i < size; i++) {
cin >> array[i];
}

int maxElement = findMax(array, size);


cout << "The maximum element in the array is: " << maxElement << endl;
return 0;
}
Sample Input: Sample Output:
5 5
12345
Aim:
To Find Factorial of the given number.
Algorithm:
Step 1:
Read the number of terms in the Fibonacci series, denoted as n.

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;
}

int first = 0, second = 1;

if (n >= 1) {
cout << first << " ";
}

if (n >= 2) {
cout << second << " ";
}

for (int i = 3; i <= n; i++) {


int next = first + second;
cout << next << " ";

first = second;
second = next;
}

cout << endl;


}

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;

void findUniqueElements(int arr[], int size) {


unordered_set<int> uniqueElements; // To store unique elements

for (int i = 0; i < size; i++) {


if (uniqueElements.find(arr[i]) == uniqueElements.end()) {
uniqueElements.insert(arr[i]); // Add it to the set
cout << arr[i] << " ";
}
}

cout << endl;


}

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];
}
}
}

for (int i = 0; i < rows1; i++) {


for (int j = 0; j < cols2; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}

return 0;
}

Sample Input: Sample Output:


33 246
33 246
111 369
111
124
123
1 23
000

Aim:
To search an element by binary search method without using recursion
Algorithm:
Step 1:
Initialize variables:

low to 0, representing the lowest index in the array.


high to size - 1, representing the highest index in the array.
ans to -1, representing the index where the element is found (initialize as -1 to indicate
no occurrences initially).
Step 2:
Perform a binary search within the array using a while loop:

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:

Check if ans is not equal to -1:


If true, print ans as the index where the element is found.
Otherwise, print "NO OCCURRENCES" to indicate that the element is not present in the
array.
Step 4: End the function
Program:
#include<iostream>
using namespace std;
void search(int array[],int size,int element)
{
int low=0;
int high=size-1;
int ans=-1;
while(low<=high)
{
int mid = (low+high)/2;
if(array[mid]==element)
{
ans= mid;
break;
}
else if(array[mid]<element)
low=mid+1;
else
high=mid-1;
}
if(ans!=-1)
{
cout<<ans;
}
else
{
cout<<"NO OCCURRENCES";
}
}
int main()
{
int num;
cin>>num;
int a[num];
for(int i=0;i<num;i++)
{
cin>>a[i];
}
int no;
cin>>no;
search(a,num,no);
}
Sample Input: Sample Output:
5 NO OCCURRUENCES
12345
6

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:

Calculate the remainder when decimal is divided by 2, and store it in a variable,


remainder.
Step 5:
Push the remainder onto the binaryDigits stack.

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;

void decimalToBinary(int decimal) {


stack<int> binaryDigits;
if (decimal == 0) {
binaryDigits.push(0);
}
while (decimal > 0) {
int remainder = decimal % 2;
binaryDigits.push(remainder);
decimal = decimal / 2;
}
while (!binaryDigits.empty()) {
cout << binaryDigits.top();
binaryDigits.pop();
}
cout << endl;
}

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:

Let textLength be the length of the text string.


Let patternLength be the length of the pattern string.
Step 3:
Initialize a loop that iterates through the text string from index 0 to textLength -
patternLength:

For each position i in the text string, do the following:


Step 3.1:
Initialize a variable j to 0.

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."

Step 4: End the program.


Program:

#include <iostream>
#include <string>
using namespace std;

void bruteForceStringMatch(const string& text, const string& pattern) {


int textLength = text.length();
int patternLength = pattern.length();

for (int i = 0; i <= textLength - patternLength; i++) {


int j;
for (j = 0; j < patternLength; j++) {
if (text[i + j] != pattern[j]) {
break;
}
}
if (j == patternLength) {
cout << "Pattern found at index " << i << endl;
}
}
}

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

You might also like