Write a program to find the sum of digits of a given number using recursion
Example:
Input: n = 12345 Output: Sum of digits is 15
Approach
C
#include <stdio.h>int sumDigits(int n){if (n < 10)return n;return n % 10 + sumDigits(n / 10);}int main(){int n;printf("Enter a number: ");scanf("%d", &n);int sum = sumDigits(n);printf("Sum of digits is %d", sum);return 0;}
Java
import java.util.Scanner;public class DigitNumSum {public static void main(String[] args) {System.out.println("Enter the number");Scanner sc = new Scanner(System.in);int n = sc.nextInt();int sum = sumDigits(n);System.out.println("Sum of digits is " + sum);sc.close();}private static int sumDigits(int n) {if (n < 10)return n;return n % 10 + sumDigits(n / 10);}}
No comments:
Post a Comment