Write a program which takes a number n as input and prints YAYY if the sum of all digits
except the rightmost digit is equal to the rightmost digit., otherwise print OOPS. (10 marks)
For example: If user enters 2237, it will print YAYY because 2+2+3 is equal to 7.
Whereas, if user enters 3425, it will print OOPS because 3+4+2 is not equal to 5. Without using loops
#include <iostream>
using namespace std;
int digits_sum(int n) {
if (n == 0)
return 0;
return n%10 + digits_sum(n/10);
}
bool check(int n) {
int d, sum;
d = n % 10;
sum = digits_sum(n/10);
return sum == d;
}
int main() {
int n;
cin >> n;
if (check(n)) {
cout << "YAYY" << endl;
}
else {
cout << "OOPS" << endl;
}
return 0;
}
Comments
Leave a comment