What is the value of the variable sum after the execution of the following code? int sum = 0, i = 1; while(i <= 5) { sum += i; i++; }
Understand the Problem
The question is asking for the final value of a variable after executing a given block of code that sums integers from 1 to 5 using a while loop.
Answer
$15$
Answer for screen readers
The final value of the variable sum is $15$.
Steps to Solve
-
Initialize Variables
The code starts by initializing two variables:
$$ \text{sum} = 0, , i = 1 $$ -
While Loop Condition
The condition for the while loop is $i \leq 5$. This means the loop will continue executing as long as $i$ is less than or equal to 5. -
Loop Execution Steps
-
First Iteration:
- Current $i = 1$
- Update sum:
$$ \text{sum} += i \Rightarrow \text{sum} = 0 + 1 = 1 $$ - Increment $i$:
$$ i = 1 + 1 = 2 $$
-
Second Iteration:
- Current $i = 2$
- Update sum:
$$ \text{sum} += i \Rightarrow \text{sum} = 1 + 2 = 3 $$ - Increment $i$:
$$ i = 2 + 1 = 3 $$
-
Third Iteration:
- Current $i = 3$
- Update sum:
$$ \text{sum} += i \Rightarrow \text{sum} = 3 + 3 = 6 $$ - Increment $i$:
$$ i = 3 + 1 = 4 $$
-
Fourth Iteration:
- Current $i = 4$
- Update sum:
$$ \text{sum} += i \Rightarrow \text{sum} = 6 + 4 = 10 $$ - Increment $i$:
$$ i = 4 + 1 = 5 $$
-
Fifth Iteration:
- Current $i = 5$
- Update sum:
$$ \text{sum} += i \Rightarrow \text{sum} = 10 + 5 = 15 $$ - Increment $i$:
$$ i = 5 + 1 = 6 $$
-
First Iteration:
-
End of Loop
Now $i = 6$, which is greater than 5, so the while loop stops executing. The final value of sum is 15.
The final value of the variable sum is $15$.
More Information
The sum of the integers from 1 to 5 is a common arithmetic series. The formula to calculate the sum of the first $n$ integers is given by:
$$ S_n = \frac{n(n + 1)}{2} $$
For $n = 5$, it becomes:
$$ S_5 = \frac{5(5 + 1)}{2} = \frac{5 \times 6}{2} = 15 $$
Tips
- Confusing the condition of the loop and including the next value of $i$. Make sure to only sum while $i$ is less than or equal to 5.
- Forgetting to increment $i$ within the loop, leading to an infinite loop.
AI-generated content may contain errors. Please verify critical information