Saturday, 8 July 2017

Java Code to sum the digits in an integer

Problem:

Design an algorithm to sum the digits in an integer.

Solution:

package com.myprograms;

import java.util.Scanner;

public class SumOfDigits {

public static void main(String[] args) {
System.out.println("the sum of digits in given number " + sumOfDigits(getTheNumber()));
}

public static int getTheNumber(){
Scanner s = new Scanner(System.in);
System.out.println("enter the n value");
int n = s.nextInt();
s.close();
return n;
}

private static int sumOfDigits(int n){
int sum = 0;
while(n > 0){
sum = sum + (n % 10);
n = n/10;
}
return sum;
}
}


Output:

enter the n value
12345
the sum of digits in given number 15



No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...