What will the following code print?counter = 1sum = 0while counter <= 6: counter = counter + 2 sum = sum + counterprint(sum)151289
Question
What will the following code print?counter = 1sum = 0while counter <= 6: counter = counter + 2 sum = sum + counterprint(sum)151289
Solution
The code will print 16. Here's how:
- Initialize
counterto 1 andsumto 0. - Enter the while loop, since
counter(1) is less than or equal to 6. - Increment
counterby 2, makingcounternow 3. - Add
counter(3) tosum(0), makingsumnow 3. - Loop back to the start of the while loop, since
counter(3) is still less than or equal to 6. - Increment
counterby 2, makingcounternow 5. - Add
counter(5) tosum(3), makingsumnow 8. - Loop back to the start of the while loop, since
counter(5) is still less than or equal to 6. - Increment
counterby 2, makingcounternow 7. - Add
counter(7) tosum(8), makingsumnow 15. - Try to loop back to the start of the while loop, but
counter(7) is now greater than 6, so exit the loop. - Print
sum(15), which is the final output.
Similar Questions
What will be printed by the following code when it executes?sum = 0values = [1,3,5,7]for number in values:sum = sum + numberprint(sum)40716
What is the outcome of the following pseudo-code?input Counterwhile(Counter<5) do Counter=Counter+1 display Counterend-while
1 pointWhat is the output of the following code?i = 1while True: if i%2 == 0: break print(i) i += 211 21 2 3 4 5 6 ...1 3 5 7 9 11 ...
Study the following program:i = 0while i < 3: print(i) i += 1 else: print(0) 0 10 1 20 1 2 00 1 2 3
What is the output produced when this code executes?i = 1while(i<=7):i *= 2print(i)816414
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.