Java #2: A simple program
Here’s my answer to the supposedly toughest question in Chapter 2 of the text book:
// Write a program that reads in an integer between 0 and 1000 and adds all the
// digits in the integer. For example, 932 returns 14import java.util.Scanner;
public class IntAdder{
public static void main(String[] args){
int input=0;
int result=0;
Scanner sc = new Scanner(System.in);System.out.print("Enter integer: ");
input = sc.nextInt();while(input!=0){
result += input%10;
input /= 10;
}System.out.println("Sum is " + result);
}
}
Input : 123
Output: 6