While and Repeat Loops
Lesson 14 of 48 in Coddy's Swift for C Developers course.
C while and Swift while test before entering their body. A C do-while corresponds to Swift repeat-while and performs the body at least once. C accepts scalar conditions; Swift needs Bool. In either language some state change or control transfer must eventually permit the loop to stop.
This workload is halved until it reaches one, and the programs count three reductions. Swift uses += 1 instead of C increment syntax, which it does not support. Integer division here is safe because all values are small and nonnegative; other arithmetic needs its own bounds analysis.
C: complete program
main.c
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(void) {
int pending = 8, rounds = 0;
while (pending > 1) { pending /= 2; ++rounds; }
printf("%d\n", rounds);
return 0;
}
Swift: complete program
main.swift
import Foundation
var pending = 8
var rounds = 0
while pending > 1 {
pending /= 2
rounds += 1
}
print(rounds)Choose repeat-while only when a first attempt is required. A precondition-tested while may correctly run zero times.
Challenge
EasyImplement digitSum(_:) for a nonnegative integer 0 through 1000000. Return the sum of its decimal digits. Input and output are each one integer.
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 digitSum(406) == 10 && digitSum(99) == 18 && digitSum(0) == 0
}
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") }
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Swift for C Developers
1Starting Swift
Working With FilesBindings and MutationNumbers and ConversionBoolean ConditionsRecap: Fare Quote4Functions and Arrays
Functions and LabelsInout and Exclusive AccessTuples and Multiple ResultsArrays Have Value SemanticsRecap: Rising Steps2Text and Decisions
Strings and InterpolationOptionals and BindingGuard and Early ExitIf and Branch ValuesRecap: Entry Rules3Control Flow
Switch and PatternsEnums as Finite ChoicesFor Loops and RangesWhile and Repeat LoopsRecap: Sequence ScanPractice on your own: Swift playground