GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

SOLVED: Day 6 While Loops Test

Forums > 100 Days of SwiftUI

The question below only prints 4 lines of text, when average score = 5.0, 7.5, 10, 12.5. I answered FALSE, but this was marked incorrect. Is this an error, or am i missing something? Shouldn't it only print 5 lines if the "averageScore += 2.5" line was after the print() statement?

While loops Question 11/12: This loop prints five lines of text – true or false?

Hint: Click to show.

var averageScore = 2.5
while averageScore < 15.0 {
    averageScore += 2.5
    print("The average score is \(averageScore)")
}

   

Unroll the loop to see what's going on.

We start with averageScore set to 2.5

  1. First time through the loop, averageScore is 2.5, therefore averageScore < 15.0 is true, so:
    • add 2.5 to averageScore
    • prints: The average score is 5.0
  2. Second time through the loop, averageScore is 5.0, therefore averageScore < 15.0 is true, so:
    • add 2.5 to averageScore
    • prints: The average score is 7.5
  3. Third time through the loop, averageScore is 7.5, therefore averageScore < 15.0 is true, so:
    • add 2.5 to averageScore
    • prints: The average score is 10.0
  4. Fourth time through the loop, averageScore is 10.0, therefore averageScore < 15.0 is true, so:
    • add 2.5 to averageScore
    • prints: The average score is 12.5
  5. Fifth time through the loop, averageScore is 12.5, therefore averageScore < 15.0 is true, so:
    • add 2.5 to averageScore
    • prints: The average score is 15.0
  6. Sixth time through the loop, averageScore is 15.0, therefore averageScore < 15.0 is false, so end the loop.

So we print 5 times.

edit: sorry, I confused myself because I was trying to do two things at once. I've corrected my post now.

1      

Hacking with Swift is sponsored by Alex.

SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!

Try for free!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.