Q:

Write a Java program to accept any number from the user and print the sum of the digits of the number. For example, if the user input is 456, the program should display the answer 15, which is 4+5+6

0

Write a Java program to accept any number from the user and print the sum of the digits of the number. For example, if the user input is 456, the program should display the answer 15, which is 4+5+6.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import java.util.Scanner;

public class Main
{
	public static void main(String[] args) {

   Scanner s = new Scanner(System.in);
   int  num, sum = 0, r; 
            System.out.println ("Enter a number : "); 
            num = s.nextInt();            
           while (num != 0) 
           {      r = num % 10;        
           num = num / 10;            
           sum = sum + r; 
               
           }
           System.out.println("Sum of Digits of the Number : "+sum); 
	}
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now