C++ Program for modular search and linear search using recursion function | C++ Programming

C++ Program for modular search and linear search using recursion function


Before starting with the program to find binary search and linear search using recursion function let us know about recursion function and Modular Search.


Recursion Function

Recursion is a process by which a function call itself repeatedly until some specified condition has been satisfied.
                
The process is used for repetitive computation in which action is stated in terms of previous result.
                
In order to solve a problem recursively two condition must be satisfied.
  • The problem must be written in a recursive form.
  • The problem statement must include a problem stopping condition.


Modular Search

It is the type of search in which we use mod recursively to find the item which is searched in the program.


C++ Program for linear search using recursion function


#include<iostream>
using namespace std;

int recursiveLinearSearch(int array[],int key,int size)
{
size=size-1;
if(size <0)
{
return -1;
}
else if(array[size]==key){
return 1;
}
else{
return recursiveLinearSearch(array,key,size);
}
}


int main()
{

cout<<"Enter The Size Of Array: ";
int size;
cin>>size;
int array[size], key,i;

// Taking Input In Array
for(int j=0;j<size;j++)
{
cout<<"Enter "<<j<<" Element : ";
cin>>array[j];
}
//Your Entered Array Is
for(int a=0;a<size;a++)
{
cout<<"array[ "<<a<<" ] = ";
cout<<array[a]<<endl;
}
cout<<"Enter Key To Search in Array";
cin>>key;
int result;
result=recursiveLinearSearch(array,key,size--);
if(result==1)
{
cout<<"Key Found in Array ";
}
else{
cout<<"Key NOT Found in Array ";
}
return 0;
}


C++ Program for modular search and using recursion function

#include <iostream>
using namespace std;
int mod (int x, int y, int a)
{
if (x == 0)
return 0;
if (y == 0)
return 1;
// If y is even
long temp;
if (y % 2 == 0) {
temp = mod(x, y / 2, a);
temp = (temp * temp) % a;
}
// If y is odd
else {
temp = x % a;
temp = (temp * mod(x, y - 1, a) % a) % a;
}
return (int)((temp + a) % a);
}
int main()
{
int x,y,a;
cout<<"x^y (mod a)"<<endl;
cout<<"Enter Base Value: ";
cin>>x;
cout<<"Enter Exponent: ";
cin>>y;
cout<<"Enter Modular Value: ";
cin>>a;
long temp;
temp= mod(x,y,a);
cout<<x <<" ^ "<<y <<" (mod "<<a<<")"<<" = "<<temp;
}

Comments

Popular posts from this blog

C Program for SCAN Disk Scheduling Algorithm | C Programming

C program to Find Cartesian Product of Two Sets | C programming

C Program To Check The String Is Valid Identifier Or Not | C Programming