Find sum of digits in java
import java.util.Scanner;
public class SumOfDigits{
public static void getSumOfDigits(int enteredNumber){
int remainder=0,sumUp=0;
do{
remainder=enteredNumber%10; //get remainder value
enteredNumber=enteredNumber/10; //get divided value
sumUp+=remainder;
}while(enteredNumber>10);
System.out.println(enteredNumber+sumUp);
}
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int number=sc.nextInt();
getSumOfDigits(number);
sc.close();//always close the scanner.
}
}
output: Enter the number: 123
6
output is calculated like this..1+2+3=6;
public class SumOfDigits{
public static void getSumOfDigits(int enteredNumber){
int remainder=0,sumUp=0;
do{
remainder=enteredNumber%10; //get remainder value
enteredNumber=enteredNumber/10; //get divided value
sumUp+=remainder;
}while(enteredNumber>10);
System.out.println(enteredNumber+sumUp);
}
public static void main(String [] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number: ");
int number=sc.nextInt();
getSumOfDigits(number);
sc.close();//always close the scanner.
}
}
output: Enter the number: 123
6
output is calculated like this..1+2+3=6;
Comments
Post a Comment