C++ Programming Please write a recursive function to find the sum of the digits
ID: 659316 • Letter: C
Question
C++ Programming
Please write a recursive function to find the sum of the digits in an integer n.
Prototype for this function is: int sum_of_digits(int n);
Please write the function and test it with a main program which prompts user for an integer input, gets the input from the user, calls the function with the input and then prints out the answer returned by the function.
Example Execution:
Please enter an integer that you would like to get the sum of the digits of: 25318
The sum of the digits for 25318 is 19.
Explanation / Answer
/*C++ program that prompts the user to enter a integer value and then calculates
the sum of the digits in the integer value and prints the sum value on console output*/
//Header file
#include<iostream>
using namespace std;
//function prototype to calculate the sum of digits in a number,n
int sum_of_digits(int n);
//starting point of program execution
int main()
{
//Declare an integer variable to read a number from user
int n;
cout<<"Please enter an integer that you would like to get the sum of the digits of: ";
//prompt user to read a number ,n
cin>>n;
//calling the method sum_of_digits with input argument n and the method
//returns the sum as its return value
int sum=sum_of_digits(n);
//print the sum of the digits in the given n value
cout<<"The sum of the digits for "<<n<<" is "<<sum<<endl;
//pause the program output
system("pause");
//returns 0
return 0;
}
/*The method sum_of_digits that accepts the input argument and
checks whether given number is not equal to zero then applies modulo
operator on n value and add calls the method sum_of_digits with input n division by
10 until n not equal to zero otherwise return zero*/
int sum_of_digits(int n)
{
//base condtion to terminate the recursive method calling
if(n!=0)
//calling sum_of_digits recursviely until n !=0
return n%10+sum_of_digits(n/10);
else
//returns zero if number is zero
return 0;
}
---------------------------------------------------------------------------------------------------------------------
sample output:
Please enter an integer that you would like to get the sum of the digits of: 25318
The sum of the digits for 25318 is 19
Hope this helps you
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.