Write a recursive function power (base, exponent) that when invoked returns For
ID: 3858448 • Letter: W
Question
Write a recursive function power (base, exponent) that when invoked returns For example, power (3, 4) = 3 * 3 * 3 * 3. Assume that exponent is an integer greater than or equal to 1. (Recursive Greatest Common Divisor) The greatest common divisor of integers x and y is the largest integer that evenly divides both x and y. Write a recursive function gcd that returns the greatest common divisor of x and y. The gcd of x and y is defined recursively as follows: If y is equal to 0, then gcd(x, y) is x; otherwise gcd(x, y) is gcd(y, x % y), where % is the remainder operator. (Find the Minimum Value in an array) Write a recursive function that takes an integer array and the array size as arguments and returns the smallest element of the array. The function should stop processing and return when it receives an array of one element. Write the int main(void) function as a driver program and call the above three functions result with sample Input/Output.Explanation / Answer
#include <iostream>
using namespace std;
int power_fun(int, int);
int gcd(int n1, int n2);
int rec(int a[],int n);
int main()
{
int base, powerRaisedto, result;
cout << "Enter base number: ";//ASKING BASE VALUE FROM USER
cin >> base;//reading value of base variable
cout << "Enter power number(positive integer): "; //power value input
cin >> powerRaisedto;//reading value of powerRaisedto variable
result = power_fun(base, powerRaisedto); //power_fun calling it jumps to power_fun function ans execute function
cout << base << "^" << powerRaisedto << " = " << result;//it will print answer
// for gcd
int n1, n2;
cout << "Enter two positive integers: ";//two input from user
cin >> n1 >> n2;//read input
cout << "G.C.D of " << n1 << " & " << n2 << " is: " << gcd(n1, n2);//calling gcd function
//for array minimm element
int i,j,n,a[20];
cout<<"enter n :";
cin>>n;
cout<<"enter values : ";
for(i=0;i<n;i++)
{
cin>>a[i];
}
cout<<" "<<rec(a,n);
return 0;
}
int power_fun(int base, int powerRaisedto)
{
if (powerRaisedto != 1) //checking value is not equal to 1 then do following
return (base*power_fun(base, powerRaisedto-1));//suppose base 3 and power is 4 then 3,3^(4-1) and call again same function and return final vale from function
else
return 1;
}
int gcd(int n1, int n2)
{
if (n2 != 0)//if no is not then (3 ,4)
return gcd(n2, n1 % n2);// (4,3%4) till not zero
else
return n1;
}
int rec(int a[],int n)
{
int min;
if(n==1)//if only one elemnt in array
return a[0];//returnn same element i.e at position 0 as minimum
else
{
min=rec(a,n-1);//if array elements are 3 n=3 and value 3 78 45
//rec(3,3-1)
if(min<a[n-1])//if min< array position [n-1] i.e 3-2=2 position
{
return min;//then reurn value in min
}
else
return a[n-1];//else a[n-1]
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.