In: Computer Science
Code needed in C++
(nOT IN STEP BY STEP EITHER)
Write a recursive function that computes the sum of the digits in an integer. Use the following function header:
int sumDigits(int n)
For example, sumDigits(234) returns 2 + 3 + 4 = 9.
Write a test program that prompts the user to enter an integer and displays its sum.
Source Code:
Output:
Code in text format (See above images of code for indentation):
#include <iostream>
using namespace std;
/*main function*/
int main()
{
/*function prototype*/
int sumDigits(int);
/*variables*/
int n,sum;
/*read an integer from user*/
cout<<"Enter an integer: ";
cin>>n;
/*function call*/
sum=sumDigits(n);
/*print sum*/
cout<<"The sum of digits is: "<<sum;
return 0;
}
/*function definition*/
int sumDigits(int n)
{
if(n==0)
return n;
/*recursive call by adding digits*/
else
return
(n%10)+sumDigits(n/10);
}