Developing Algorithms Using Strings

AP Computer Science A· difficulty 4/5

int n = 1234;
int sum = 0;
while (n > 0) {
  sum += n % 10;
  n /= 10;
}
System.out.println(sum);

What is printed?

  • A

    1234

  • B

    9

  • C

    4321

  • D

    10

    check_circle

Explanation

Each iteration extracts the last digit and divides off. 1234 -> sum 4, n=123 -> sum 7, n=12 -> sum 9, n=1 -> sum 10, n=0 stop. Sum = 1+2+3+4 = 10.

Want 10 more like this — adaptive to your weak spots?

Related questions