In: Computer Science
a. Write a c++ function called IsPalindrome that receives a 3-digit number and returns whether it is palindrome or not. [2.5 marks]
b. Write a c++ function, called GCD that receives two parameters n, d, and prints their greatest common divisor [2.5 marks]
Once the user select one of the above choices you have to read the value entered by the user and then to call the respective function.
#include <iostream>
using namespace std;
//function to find if number is palindrome
int IsPalindrome()
{
int p;
do{
cout<<"Enter a three digit number: ";
cin>>p;
}while(p>999 ||p<100);
if(p%10==p/100) //if first and last digit(of 3 digit number) are same then it is palindrome
{
cout<<"The number is palindrome\n";
return 1; //return 1 if it is palindrome
}
else
{
cout<<"The number is not palindrome\n";
return 0; //returning 0 if it is not palindrome
}
}
// function to find gcd
void GCD(int n, int d)
{
int gcd;
for(int i=1; i <= n && i <= d; ++i)
{
// Checks if i is factor of both integers
if(n%i==0 && d%i==0)
gcd = i;
}
//printing gcd of both numbers
cout<<"The gcd of numbers "<<n<<" and "<<d<<" is: "<<gcd<<endl;
}
//function to display menu
void menu()
{
cout<<"Enter 1 to use find palindrome: \n";
cout<<"Enter 2 to use find GCD: \n";
cout<<"Enter 3 to use find Exit: \n";
}
int main()
{
int choice,n,d,p;
// loop to ask user for his/her choice
while (1)
{
menu(); //calling menu function
cin>>choice; //taking input foe choice
switch (choice)
{
case 1: //if user chosses 1
IsPalindrome(); //calling palindrome function
break;
case 2: //if user chooses 2
cout << "Enter two numbers: "; //asking for input for gcd function
cin >> n >> d; //taking input from user
GCD(n,d); //calling function
break;
case 3: //if user enters 3
exit(0);
break;
default: //if user enters invalid input
cout << "Invalid input" << endl;
}
}
return 0;
}
ss for reference: