C A Implement the recursive algorithms in the notes titled R

C++

A. Implement the recursive algorithms in the notes titled Recursion1: factorial, sum, Fibonacci, print, & palindrome.

B. Implement a recursive algorithm to sum the first N integers and compare the run times with the iterative algorithm that you (may have) implemented in Problem 1.

Solution

A.

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

int factorial(int number) { //recursive factorial function
   int fact;

   if(number <= 1) return 1;

   fact = number * factorial(number - 1);
   return fact;
}

int sum(int n) //recursive sum function
{
if(n != 0)
return n + sum(n - 1);
return 0;
}

void print(int n){ //recursive print function
if(n==1){
cout<<n;
return ;
}
print(n-1);


}

int fibonacci(int n) { //recursive fibbonacci function
if (n == 0)
{
return 0;
}   
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1) + fibonacci(n-2);
}

  
  
}


bool isPalin(int start, int end, string &str) //recursive palindrome function
{
if (start >= end) // all characters in string are checked
return true;
if (toupper(str[start]) != toupper(str[end])) //compare 1st character with last,2nd with second last and so on after capitalizing
return false;
return isPalin(++start, --end, str); // increment start index and decrement end index
}

int main()
{
string str;
int length;
cout<<\"Enter the String to check:\";
cin>>str;
length = str.length();
if(isPalin(0,length-1,str))
cout<<\"\ \"<<str<<\" is a palindrome\";
else
cout<<\"\ \"<<str<<\" is not a palindrome\";

cout<<\"\ Factorial of 5 =\"<<factorial(5);
cout<<\"\ Sum of first 10 natural numbers = \"<<sum(10);
cout<<\"\ Print numbers :\";
print(10);
cout<<\"\ Fibonacci term 8 :\"<<fibonacci(8);

return 0;
}

output:

B.

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

int sum(int n) //recursive sum function
{
if(n != 0)
return n + sum(n - 1);
return 0;
}


int main()
{
cout<<\"\ Sum of first 10 natural numbers = \"<<sum(10);

return 0;
}

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

int sum(int n) //iterative sum function
{
int i,s=0;
for(i=1;i<=n;i++)
{
   s = s+ i;
}
return s;
}


int main()
{
cout<<\"\ Sum of first 10 natural numbers = \"<<sum(10);

return 0;
}

Iterative function is faster than recursive function

C++ A. Implement the recursive algorithms in the notes titled Recursion1: factorial, sum, Fibonacci, print, & palindrome. B. Implement a recursive algorithm
C++ A. Implement the recursive algorithms in the notes titled Recursion1: factorial, sum, Fibonacci, print, & palindrome. B. Implement a recursive algorithm
C++ A. Implement the recursive algorithms in the notes titled Recursion1: factorial, sum, Fibonacci, print, & palindrome. B. Implement a recursive algorithm

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site