Menu
Coddy logo textTech

While Loop

Part of the Fundamentals section of Coddy's Swift journey — lesson 43 of 86.

Sometimes you don't know exactly how many times a loop should run. Instead, you want to keep looping while a condition remains true. That's where the while loop comes in.

var count = 1

while count <= 3 {
    print(count)
    count += 1
}
// Output: 1, 2, 3 (each on a new line)

The loop checks the condition count <= 3 before each iteration. As long as it's true, the code inside runs. Once the condition becomes false, the loop stops.

Be careful: if the condition never becomes false, you'll create an infinite loop! Always make sure something inside the loop eventually changes the condition:

var number = 10

while number > 0 {
    print(number)
    number -= 2
}
// Output: 10, 8, 6, 4, 2

Use a while loop when the number of iterations depends on a condition that changes during execution, rather than a fixed range.

challenge icon

Challenge

Easy
Write a function countdownSum that takes start and returns the sum of all numbers from start down to 1.

Use a while loop to count down from the starting number, adding each value to a running total until you reach zero.

Logic:

  • Start with the given number
  • While the number is greater than 0, add it to the sum and decrease by 1
  • Return the final sum

Parameters:

  • start (Int): The starting number for the countdown

Returns: The sum of all numbers from start down to 1 (Int)

For example, if start is 5, the function calculates 5 + 4 + 3 + 2 + 1 = 15 and returns 15.

Cheat sheet

A while loop repeats code as long as a condition is true:

var count = 1

while count <= 3 {
    print(count)
    count += 1
}
// Output: 1, 2, 3

The condition is checked before each iteration. When it becomes false, the loop stops.

Always ensure the condition eventually becomes false to avoid infinite loops:

var number = 10

while number > 0 {
    print(number)
    number -= 2
}
// Output: 10, 8, 6, 4, 2

Use while loops when the number of iterations depends on a changing condition rather than a fixed range.

Try it yourself

func countdownSum(start: Int) -> Int {
    // Write code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals