uint sum = 0; for (uint i = 1; i <= 3; i++) { sum += i; } return sum;
medium
A. 6
B. 3
C. 0
D. Error
Solution
Step 1: Analyze the loop iterations
The loop runs with i = 1, 2, 3. Each time, sum adds i: sum = 0+1, then 1+2, then 3+3.
Step 2: Calculate the final sum
Sum after loop: 0+1=1, 1+2=3, 3+3=6.
Final Answer:
6 -> Option A
Quick Check:
1+2+3 = 6 [OK]
Hint: Add numbers from 1 to 3 to get sum quickly [OK]
Common Mistakes:
Stopping loop early
Adding wrong values
Confusing sum initialization
4. Identify the error in this code snippet:
uint i = 0; while (i < 3) i++;
medium
A. Condition should be i <= 3
B. Missing braces {} for while loop body
C. Variable i should start at 1
D. Incorrect increment operator
Solution
Step 1: Check loop body syntax
The while loop lacks braces {}, so only the next statement is inside the loop.
Step 2: Understand impact of missing braces
Without braces, the loop runs only the single statement i++;. This is valid but can cause confusion or errors if more statements are added.
Final Answer:
Missing braces {} for while loop body -> Option B
Quick Check:
Always use braces for clarity in loops [OK]
Hint: Use braces {} to clearly define loop body [OK]
Common Mistakes:
Assuming multiple statements run without braces
Changing variable start unnecessarily
Altering loop condition wrongly
5. You want to create a loop that counts down from 5 to 1 and stores each number in an array. Which code snippet correctly uses a for loop to do this in blockchain programming?
A) for (uint i = 5; i > 0; i--) { arr.push(i); } B) for (uint i = 1; i <= 5; i++) { arr.push(i); } C) for (uint i = 5; i >= 1; i++) { arr.push(i); } D) for (uint i = 5; i > 0; i++) { arr.push(i); }
hard
A. Infinite loop due to i++ with i > 0
B. Counts up from 1 to 5
C. Infinite loop due to i++ with i >= 1
D. Counts down from 5 to 1 correctly
Solution
Step 1: Analyze each loop's counting direction
Counts down from 5 to 1 correctly counts down from 5 to 1 using i-- and condition i > 0. Counts up from 1 to 5 counts up. Options C and D increase i but have conditions that cause infinite loops.
Step 2: Confirm correct loop behavior
Counts down from 5 to 1 correctly correctly pushes 5,4,3,2,1 into the array and stops when i reaches 0.
Final Answer:
Counts down from 5 to 1 correctly -> Option D
Quick Check:
Decrement i with i-- and condition i > 0 for countdown [OK]
Hint: Use i-- and i > 0 to count down safely [OK]
Common Mistakes:
Using i++ when counting down
Wrong loop condition causing infinite loops
Confusing counting up vs down
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.