Sum of Digits of a Number pr a Given Number ~ IN JAVA

Document

PROGRAME THAT CALULATED SUM OF DIGITS OF A GIVEN NUMBER IN JAVA

import java.util.Scanner; public class SumOfDigitsOfaNumber { public static void main(String[] args) { System.out.println(sumOfDigitOfANumber(input("Sum of Digits of a Number \n Enter your number: "))); } // These function use for taking input from user private static int input(String command) { Scanner input = new Scanner(System.in); System.out.print(command); return input.nextInt(); } // The function are use of sum the digit of a integer or number private static long sumOfDigitOfANumber(int number){ int i = 0; long digit = 1, result = 1; while (i < number){ digit = number % 10; //finds the last digit of the given number for e.g digit (123 % 10) = 3; result += digit; //adds last digit to the variable sum for e.g result = 1 + digit number /= 10; //removes the last digit from the number = 12; i++; } return result; } }

Comments

Post a Comment