Problem statement:- Program to Find the sum of digits of a number using recursion.
Data requirement:-
Input Data:- num
Output Data:-SumOfDigits(int num)
Output Data:-SumOfDigits(int num)
Program in C
Here is the source code of the C Program to Find the sum of digits of a number using recursion.
Code:
#include<stdio.h>
int SumOfDigits(int num)
{
if(num>0)
return ((num%10) +SumOfDigits(num/10));
else if(num==0)
return 0;
}
int main()
{
int num;
printf("Enter the Number:");
scanf("%d",&num);
printf("Sum of digits of a given Number Using Recursion is:%d",SumOfDigits(num));
}
Enter the Number:215
Sum of digits of a given Number Using Recursion is:8
Program in C++
Here is the source code of the C++ Program to Find the sum of digits of a number using recursion.
Code:
#include<iostream>
using namespace std;
int SumOfDigits(int num)
{
if(num>0)
return ((num%10) +SumOfDigits(num/10));
else if(num==0)
return 0;
}
int main()
{
int num;
cout<<"Enter the Number:";
cin>>num;
cout<<"Sum of digits of a given Number Using Recursion is:"<<SumOfDigits(num);
}
Enter the Number:4563
Sum of digits of a given Number Using Recursion is:18
Program in Java
Here is the source code of the Java Program to Find the sum of digits of a number using recursion.
Code:
import java.util.Scanner;
public class SumOfDigitsGivenNumber {
static int SumOfDigits(int num)
{
if(num==0)
return 0;
else
return ((num%10) +SumOfDigits(num/10));
}
public static void main(String[] args) {
Scanner cs=new Scanner(System.in);
System.out.print("Enter the Number:");
int n=cs.nextInt();
System.out.print("Sum of digits of given Number Using Recursion is:"+SumOfDigits(n));
cs.close();
}
}
Enter the Number:1432789
Sum of digits of given Number Using Recursion is:34
Program in Python
Here is the source code of the Python Program to Find the sum of digits of a number using recursion.
Code:
def SumOfDigits(num):
if num==0:
return 0
else:
return ((num%10) +SumOfDigits(num//10))
num=int(input("Enter the Number:"))
print("Sum of digits of given Number Using Recursion is:",SumOfDigits(num))
Enter the Number:9874879
Sum of digits of given Number Using Recursion is: 52
Most Recommend Questions:-
More Questions:-
0 Comments
Please do not Enter any spam link in the comment box