Write a recursive function, power, that takes as parameters two integers x and y
ID: 3762245 • Letter: W
Question
Write a recursive function, power, that takes as parameters two integers x and y such that x is nonzero and returns x^y, For y 0: Prompt user for x and y. If user enters non-integers, then catch the exception and prompt again. Write a recursive function sumDigits that takes an integer as a parameter and returns the sum of the digits of the integer. Prompt for the integer for the user, if user enters invalid value, then catch the exception and prompt again. Write your own exception class invalidInt with what() function.Explanation / Answer
#include<iostream>
#include<string.h>
#include<exception>
using namespace std;
class invalidInt : public exception {
public:
virtual const char* what() const throw() override
{
return "not an integer!!";
}
};
int sumDigits(int n) {
if (n==0) {
return 0;
}
return n%10 + sumDigits(n/10);
}
int main() {
int in;
while (true) {
try {
cout<<" Enter int: ";
cin>>in;
if (cin.fail()) {
cin.clear();
cin.ignore();
throw invalidInt();
}
break;
} catch(exception &e) {
cout<<e.what()<<" ";
}
}
cout<<" Sum of digits: "<<sumDigits(in);
cout<<" ";
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.