Menu
Coddy logo textTech

Closed vs Half-Open

Part of the Logic & Flow section of Coddy's Swift journey — lesson 7 of 56.

Swift has two range operators that look almost identical but mean different things.

a...b is the closed range. It includes b:

for i in 1...3 { print(i) }
// 1
// 2
// 3

a..<b is the half-open range. It stops before b:

for i in 1..<3 { print(i) }
// 1
// 2

Half-open is the natural fit when you have a count: 0..<arr.count covers every valid index of the array. Use closed when both ends are real values you care about (like a score range or an inclusive grade boundary).

challenge icon

Challenge

Easy

Read two integers (two lines): a and b, with a <= b. Print three lines:

  1. The values in the closed range a...b, joined with , on one line
  2. The values in the half-open range a..<b, joined with , (or an empty line when the range is empty)
  3. The sum of every value in the closed range

For input 1 then 5, the output is:

1,2,3,4,5
1,2,3,4
15

Cheat sheet

Range operators in Swift:

  • a...bclosed range, includes both a and b
  • a..<bhalf-open range, includes a but stops before b
for i in 1...3 { print(i) } // 1, 2, 3
for i in 1..<3 { print(i) } // 1, 2

Use 0..<arr.count to cover every valid array index. Use closed ranges when both endpoints are meaningful values.

Try it yourself

let a = Int(readLine()!)!
let b = Int(readLine()!)!

// TODO: print closed range joined, half-open range joined, sum of closed range
quiz iconTest yourself

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

All lessons in Logic & Flow