You want to create a procedure that sums numbers from 1 to N using a WHILE loop. Which of these code snippets correctly implements this?
hard📝 Application Q15 of 15
SQL - Stored Procedures and Functions
You want to create a procedure that sums numbers from 1 to N using a WHILE loop. Which of these code snippets correctly implements this?
ADECLARE @sum INT = 0;<br>WHILE @sum <= @N<br>BEGIN<br> SET @sum = @sum + 1;<br>END
BDECLARE @sum INT = 0, @i INT = 1;<br>WHILE @i < @N<br>BEGIN<br> SET @sum = @sum + @i;<br>END
CDECLARE @sum INT = 0, @i INT = 1;<br>WHILE @i <= @N<br>BEGIN<br> SET @sum = @sum + @i;<br> SET @i = @i - 1;<br>END
DDECLARE @sum INT = 0, @i INT = 1;<br>WHILE @i <= @N<br>BEGIN<br> SET @sum = @sum + @i;<br> SET @i = @i + 1;<br>END
Step-by-Step Solution
Solution:
Step 1: Check loop condition and variable updates
DECLARE @sum INT = 0, @i INT = 1; WHILE @i <= @N BEGIN SET @sum = @sum + @i; SET @i = @i + 1; END correctly loops from 1 to N, adding each number to sum and incrementing i.
Step 2: Identify errors in other options
DECLARE @sum INT = 0, @i INT = 1; WHILE @i < @N BEGIN SET @sum = @sum + @i; END misses increment of i, causing infinite loop. DECLARE @sum INT = 0, @i INT = 1; WHILE @i <= @N BEGIN SET @sum = @sum + @i; SET @i = @i - 1; END decrements i, causing infinite loop. DECLARE @sum INT = 0; WHILE @sum <= @N BEGIN SET @sum = @sum + 1; END incorrectly uses sum as loop variable.
Final Answer:
DECLARE @sum INT = 0, @i INT = 1; WHILE @i <= @N BEGIN SET @sum = @sum + @i; SET @i = @i + 1; END -> Option D
Quick Check:
Increment loop variable and add to sum = A [OK]
Quick Trick:Increment loop counter and add to sum inside WHILE [OK]
Common Mistakes:
Forgetting to increment loop variable
Decrementing loop variable causing infinite loop
Using sum as loop condition variable
Master "Stored Procedures and Functions" in SQL
9 interactive learning modes - each teaches the same concept differently