105k views
2 votes
What is the output of the following code fragment? int i = 1; int sum = 0; while (i <= 15) { sum = sum + i; i++; } System.out.println("The value of sum is " + sum);

User Amir Doreh
by
4.9k points

1 Answer

2 votes

Answer:

The value of sum is 120

Step-by-step explanation:

Consider the same code snippet numbered below:

  1. int i = 1;
  2. int sum = 0;
  3. while (i <= 15) {
  4. sum = sum + i;
  5. i++;
  6. }
  7. System.out.println("The value of sum is " + sum);
  8. }

Line 1 Initializes an int variable i to 1

Line 2 creates another int variable sum, sets it to 0

line 3 has a while statement that executes until i becomes equal to 15

In line 4 the current value of sum is continuously added to i as long as the condition in line 3 stays true.

Line 5 ensures there is no infinite loop by increasing i by 1

At line 7 The value of the variable sum will be 120. This is the sum of numbers from 1 to 15. and it is printed to the console.

User Kajuan
by
4.9k points