Challenge 1 - SumDigits.java
Write a program that reads an integer between 0 and 1000 and adds all the digits in the integer. For example, if an integer is 837, the sum of all digits is 18.
Sample output: Enter an integer between 0 and 1000: 837 The sum of all digits in 837 is 18
//SumDigits.java import java.util.Scanner; public class SumDigits { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); int n; System.out.print("Enter an integer between 0 and 1000: "); n = scanner.nextInt(); System.out.println("The sum of all digits in 837 is "+sumOfDigits(n)); } public static int sumOfDigits(long n){ int result = 0; while(n>0){ result += (n%10); n = n / 10; } return result; } }
Get Answers For Free
Most questions answered within 1 hours.