Menu
CoddyTech

While and Repeat Loops

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

C# do ... while and Swift repeat ... while both run their body before checking the condition. Ordinary while checks first and can skip the body entirely. The example drains a pending queue count until it reaches zero, counting the iterations. Choosing the wrong loop form changes behavior at the empty boundary. Swift does not use ++ or --; write += 1 or -= 1. Ensure the body changes the state used by the condition. This is termination reasoning, separate from processing decimal digits in the exercise.

C#

Complete program file: Program.cs.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int pending = 0, visits = 0;
        do { visits += 1; pending -= 1; } while (pending > 0);
        Console.WriteLine(visits);
    }
}

Swift

Complete program file: main.swift.

var pending = 0
var visits = 0
repeat { visits += 1; pending -= 1 } while pending > 0
print(visits)
challenge icon

Challenge

Easy

Implement 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") }
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