Sum Of Digit Of A Number Using Recursion Through C++ Programming

In this post, I will discuss Sum Of Digit Of A Number Using Recursion through C++ Programming.

Given a number, we need to find sum of its digits using recursion.

Examples:

Input : 12345
Output : 15

Input : 45632
Output :20

Now, the step by step process for a better understanding of how this algorithm works,

Lets, Take the example 12345

Step-1:

12345 % 10 which is equal-too 5 + and then send 12345/10 to next step.

Step-2:

1234 % 10 which is equal-too 4 + and then send 1234/10 to next step.

Step-3:

123 % 10 which is equal-too 3 + and then send 123/10 to next step.

Step-4:

12 % 10 which is equal-too 2 + and then send 12/10 to next step.

Step-5:

 1 % 10 which is equal-too 1 and then send 1/10 to next step.

Step-6:

 0 algorithm stops.

Here, following diagram will illustrate the process of recursion:

sum-of-digit-of-a-number-using-recursion
Sum Of Digit Of Number Using Recursion
// Recursive C++ program to find sum of digits
// of a number
#include <bits/stdc++.h>
using namespace std;

// Function to check sum of digit using recursion
int sum_of_digit(int n)
{
	if (n == 0)
	return 0;
	return (n % 10 + sum_of_digit(n / 10));
}

// Driven code
int main()
{
	int num = 12345;
	int result = sum_of_digit(num);
	cout << "Sum of digits in "<< num
	<<" is "<<result << endl;
	return 0;
}

// THis code is contributed by
// SHUBHAMSINGH10

Output:

Sum of digits in 12345 is 15

Please comment and share this post and wants to add more content to this website please WhatsApp us.

Share Your Love
Default image
Lingaraj Senapati
Hey There! I am Lingaraj Senapati, the Co-founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.
Articles: 136

Newsletter Updates

Enter your email address below to subscribe to our newsletter

Leave a Reply