Question

Print sum of digits of a number using recursion

				
					ENTER THE NUMBER
1234
SUM OF DIGITS OF 1234 IS 10
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class sumOfDigits
{
    public static int CalculateSumOfDigits(int num)
    {
        if(num==0)
        {
            return 0; 
        }
        else
        {
            return num%10 + CalculateSumOfDigits(num/10);   
        }
    }

    public static void main()
    {
        int num=0,sum=0;
        Scanner sc=new Scanner(System.in);
        System.out.println("ENTER THE NUMBER");
        num=sc.nextInt();
        sum=CalculateSumOfDigits(num);
        System.out.println("SUM OF DIGITS OF "+num+" IS "+sum);
    }
}


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *