Write a program to find sum of digits of a number using recursion in C, C++. This is a simple question to understand and implement recursion concept. In this program we take a number from user then add the digits of a number recursively and finally return the result.
I already discussed the iterative version of this program. Program to calculate the sum of digits of a number.
In this program we used recursion to add digits of a number. In programming recursion and iteration are two very important concepts. Read the difference between recursion and iteration.
Output -
Enter a number : 345
Sum of digits of a number is : 12
Explanation
Suppose you have entered a number 345. Let's see how this program work.
Step 1 - 5 + addDigit (34)
Step 2 - 5 + 4 + addDigit (3)
Step 3 - 5 + 4 + 3 + addDigit (0)
Step 4 - 5 + 4 + 3 + 0
Now final result is returned.
I already discussed the iterative version of this program. Program to calculate the sum of digits of a number.
In this program we used recursion to add digits of a number. In programming recursion and iteration are two very important concepts. Read the difference between recursion and iteration.
Find Sum of Digits of a Number using Recursion in C
#include <stdio.h>
int addDigit(int num) {
if (num <= 0) {
return 0;
}
return ( num % 10) + addDigit( num / 10);
}
int main(void) {
int n, result;
printf ("Enter a number : \n");
scanf ("%d", &n);
result = addDigit(n);
printf("Sum of digits of a number is %d",result);
return 0;
}
Output -
Enter a number : 345
Sum of digits of a number is : 12
Explanation
Suppose you have entered a number 345. Let's see how this program work.
Step 1 - 5 + addDigit (34)
Step 2 - 5 + 4 + addDigit (3)
Step 3 - 5 + 4 + 3 + addDigit (0)
Step 4 - 5 + 4 + 3 + 0
Now final result is returned.
Find Sum of Digits of a Number using Recursion in C++
#include <iostream>
using namespace std;
int addDigit(int num) {
if (num <= 0) {
return 0;
}
return ( num % 10) + addDigit( num / 10);
}
int main() {
int n, result;
cout << "Enter a number \n";
cin >> n;
result = addDigit(n);
cout << "Sum of digits of a number is " << result;
return 0;
}
No comments:
Post a Comment