Assignment Recursion Part1: Palindrome detector Write a program that will test i
ID: 3536227 • Letter: A
Question
Assignment Recursion
Part1: Palindrome detector
Write a program that will test if some string is a palindrome
1. Ask the user to enter a string
2. Pass the string to a Boolean function that uses recursion to determine if something is a palindrome or not. The function should return true if the string is a palindrome and false if the string is not a palindrome.
3. Main displays the result ( if the string is a palindrome or not
Part 2: Compute the Greatest Common Factor
Write a program that computes the GCF (Greatest Common Factor) of two positive whole numbers entered by the user. For example the GCF of 24 and 18 is 6. The program will prompt the user for entering two positive whole numbers and will then return their GCF. The user may terminate the program by entering -1 for the first number. The program should provide a recursive function to compute GCF.
Test the above for at least 4 pairs of values.
Mathematical Calculation:
GCF of two whole numbers can be calculated mathematically via repeated division. For example, GCF of 16 and 26 can be found as below:
1. Divide 16 into 26. The remainder is 10.
2. Divide 10 (the remainder in the last step) into 16 (the divisor in the last step). The remainder is 6.
3. Divide 6 (the remainder in the last step) into 10 (the divisor in the last step). The remainder is 4.
4. Divide 4 (the remainder in the last step) into 6 (the divisor in the last step). The remainder is 2.
5. Divide 2 (the remainder in the last step) into 4 (the divisor in the last step). The remainder is 0. Hence GCF is 2.
Note: You are to provide a recursive function to implement the above algorithm.
Explanation / Answer
// Ans1:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char str[100];
int begin, middle, end, length = 0;
cout<<"Enter the string ";
gets(str);
while ( str[length] != '' )
length++;
end = length - 1;
middle = length/2;
for( begin = 0 ; begin < middle ; begin++ )
{
if ( str[begin] != str[end] )
{
cout<<"Not a palindrome. ";
break;
}
end--;
}
if( begin == middle )
cout<<"Palindrome. ";
return 0;
}
// Ans 2:
#include <iostream>
using namespace std;
int gcd(int num1, int num2)
{
if(num2 == 0)
{
return num1;
}
else
{
return gcd(num2, num1 % num2);
}
}
int main()
{
int num1,num2;
while(1)
{
cout << "Enter first number: or -1 to exit: ";
cin >> num1;
if(num1==-1)
break;
cout << "Enter second number: ";
cin >> num2;
cout << "Greatest common divisior (GCD) is " << gcd(num1,num2) << endl<<endl;
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.