Write a program that will ask user to enter a digit character (i.e. ‘0’ or ‘1’ .... or ‘9’). If user
enters a non-digit character then the program should display message to re-enter correct input. If user
enters a correct character (i.e. a digit character) then your program should convert that character to
a same digit but in integer type. Do this for five inputs. Finally, add all digits and display their sum. Do
not use any library function or loops.
#include <iostream>
using namespace std;
int sum(int n) {
char ch;
int d;
if (n == 0) {
return 0;
}
cin >> ch;
if (ch >= '0' && ch <= '9') {
d = ch - '0';
n--;
return d + sum(n);
}
return sum(n);
}
int main() {
int res = sum(5);
cout << res;
return 0;
}
Comments
Leave a comment