In: Computer Science
Write functions for each of the following problems. Each problem
should be solved by
writing a recursive function. Your final program should not have
any loops in it.
(a) Write a function that uses recursion to raise a number to a
power. The function should
take two arguments, the number to be raised to the power (floating
point) and the
power (a non-negative int). (10
Points)
(b) Write a boolean function named isMember that takes two
arguments: an array of type
char and a value. It should return true if the value is found in
the array, or false if the
value is not found in the array. (10 Points)
(c) A palindrome is any word, phrase, or sentence that reads the
same forwards or
backwards. Here are some palindromes:
Level
Civic
Pot top
A man a plan a canal Panama
note:your final programme must not have any loops, do it with recursion, the language must be c++, and kindly explain it in simple words in the form of comments before each part
To be as simple as possible we are designing functions sensitive to the input.
for example:
#include <iostream>
using std::cout;
float power(float a, int n){
  float temp;                 //to hold intermidiate results
  if(n == 0) return 1;        // base case
  temp = power(a, n/2);
  if(n % 2 == 0)              // if power is even
    return temp * temp;
  else{                       // if power is odd
    if(n > 0)
      return a * temp * temp;
    else
      return (temp * temp) / a;
  }
}
bool isMember(char a[], char val, int i, int l){
  if (i == l)                 // array is traversed completely
    return false;
  if (a[i] == val)            // element to be search is found at index i
    return true;
  return isMember(a, val, i + 1, l); // recursively search in remaining array
}
bool isPalindrome(char a[], int i, int l){
    if (i == l)                 // base case: If only one character is there
    return true;
    if (a[i] != a[l])           // if first and last characters do not match
    return false;               // string cannot be a palindrome
    if (i < l + 1)              // recursively check if middle array is palindrome
    return isPalindrome(a, i + 1, l - 1);
    return true;
}
int main(){
  float a = 2.5;
  int n = 3;
  char arr[] = {'h','e','l','l','o', '\0'};
  char pal[] = {'p','o','t','t','o','p','\0'};
  int p = sizeof(pal) / sizeof(pal[0]);
  int l = sizeof(arr) / sizeof(arr[0]);
  cout << power(a, n) << std::endl;
  cout << isMember(arr, 'i', 0, l) << std::endl;
  cout << isPalindrome(pal, 0, p - 2);
  return 0;
}

