Bird
0
0

Identify the bug in this balance calculation code snippet:

medium📝 Analysis Q14 of 15
LLD - Design — Splitwise (Expense Sharing)
Identify the bug in this balance calculation code snippet:
balance = 50
transactions = [10, -20, 15]
for t in transactions:
    balance = t
print(balance)
AThe initial balance is not set
BThe transactions list is empty
CThe balance is overwritten instead of updated
DThe loop variable is incorrect
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the loop operation

    Inside the loop, balance = t overwrites balance each time instead of adding.
  2. Step 2: Understand correct update

    It should be balance += t to add each transaction to balance.
  3. Final Answer:

    The balance is overwritten instead of updated -> Option C
  4. Quick Check:

    Use += to update balance, not = [OK]
Quick Trick: Use += to add transactions, not = [OK]
Common Mistakes:
  • Using = instead of += inside loop
  • Assuming transactions list is empty
  • Ignoring initial balance

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes