Thursday, June 19, 2014

Elementary Programming; Exercise No. 6

Write a program that reads an integer between  0 and 1000 and adds all the digits in the integer without loops. For example, if an integer is  932 , the sum of all its digits is  14.

Solution:

public static void main(String[] args) {
   Scanner s = new Scanner(System.in);
   int number, sum;

   System.out.print("Enter a number between 0 and 1000:");
   number = s.nextInt();

   sum = 0;
   sum += number % 10; //add the first digit to the sum
   number = number / 10; //removes  the first digit from the number
   sum += number % 10; //add the second digit to the sum
   number = number /10; //removes the second digit from the number
   sum += number % 10; //add the third digit to the sum

   System.out.print("The sum of the digits in " + number + " is " + sum + ".");
}

No comments:

Post a Comment

Author