Menu
CoddyTech

For Loops and Ranges

Lesson 13 of 48 in Coddy's Swift for C Developers course.

C for typically names initialization, condition and update explicitly. Swift for-in binds values from a sequence, with ..< excluding the upper bound and ... including it. A nonnegative count that may be zero is naturally traversed with a half-open range from zero.

The programs print three checklist lines. Swift no longer uses a C-style counter for loop, and its iteration binding is not an independently incremented variable. Prefer direct collection traversal for elements instead of inventing indices. Indices must be appropriate to the collection, especially for strings.

C: complete program

main.c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

int main(void) {
for (int index = 0; index < 3; ++index) printf("step %d\n", index);
    return 0;
}

Swift: complete program

main.swift

import Foundation
for index in 0..<3 { print("step \(index)") }

A closed Swift range with its lower bound above its upper bound is invalid. Handle empty and descending cases deliberately instead of assuming the C condition will suppress iteration.

challenge icon

Challenge

Easy

Implement multiples(upTo:of:): count multiples of the divisor in the inclusive range 0 through limit, including zero. Input is limit 0 through 1000 and divisor 1 through 100. Output the count.

Implement the required APIs and solve(_ input: String) -> String. Return output text without a final newline; do not print in editable code. The locked driver independently checks the APIs on additional valid inputs, then prints the returned text with exactly one newline. All numeric operations stay within Int bounds.

Your code goes in Functions.swift. main.swift holds the supplied input/output code and cannot be edited.

Try it yourself

import Foundation
func apiChecks(_ input: String) -> Bool {
return multiples(upTo: 14, of: 4) == 4 && multiples(upTo: 0, of: 2) == 1 && multiples(upTo: 8, of: 4) == 3
}
let input = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8)!
// BEGIN PUBLIC API PROBES
let apiOK = apiChecks(input)
// END PUBLIC API PROBES
if apiOK { print(solve(input)) } else { print("API mismatch") }
quiz iconTest yourself

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

All lessons in Swift for C Developers

Practice on your own: Swift playground