75.6k views
0 votes
Translate the following pseudocode to java. Do not write a complete program with main method, just the algorithm given. The algorithm will sum the digits of a positive integer. Assume that n was declared and assigned prior to the algorithm, all other variables used in your java code must be declared.

number = n
sumd = 0
while number > 0
add number mod 10 to sumd
number = number div 10
print that the sum of the digits of n is sumd

1 Answer

5 votes

Final answer:

The pseudocode provided is translated into Java by declaring two variables, performing a while loop to sum each digit, and printing the result.

Step-by-step explanation:

To translate the given pseudocode into Java, first declare the needed variables and then implement the logic expressed in the pseudocode to sum the digits of a positive integer. Here is the Java code equivalent to the pseudocode:

int number = n;
int sumd = 0;
while (number > 0) {
sumd += number % 10;
number /= 10;
}
System.out.println("The sum of the digits of " + n + " is " + sumd);

This snippet declares two integers, number and sumd. Then it enters a while loop, which continues as long as number is greater than zero. Inside the loop, it adds the last digit of number (number % 10) to sumd, and then truncates the last digit from number (number /= 10). Finally, it prints out the sum of the digits.

User Scott Christopher
by
8.4k points