Programming Fundamentals/Loops/Swift

loops.swift

edit
// This program demonstrates While, Do, and For loop counting using
// user-designated start, stop, and increment values.
//
// References:
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

import Foundation

func getValue(name: String) -> Int {
    var value : Int
    
    print("Enter " + name + " value:")
    value = Int(readLine()!)!
    return value
}

func whileLoop(start: Int, stop: Int, increment: Int) {
    print("While loop counting from " + String(start) + " to " + 
        String(stop) + " by " + String(increment) + ":")
    
    var count : Int
    
    count = start
    while count <= stop {
        print(count)
        count = count + increment
    }
}

func doLoop(start: Int, stop: Int, increment: Int) {
    print("Do loop counting from " + String(start) + " to " + 
        String(stop) + " by " + String(increment) + ":")
    
    var count : Int
    
    count = start
    repeat {
        print(count)
        count = count + increment
    } while count <= stop
}

func forLoop(start: Int, stop: Int, increment: Int) {
    print("For loop counting from " + String(start) + " to " + 
        String(stop) + " by " + String(increment) + ":")
    
    for count in stride(from: start, through: stop, by: increment) {
        print(count)
    }
}

func main() {
    var start : Int
    var stop : Int
    var increment : Int

    start = getValue(name: "starting")
    stop = getValue(name: "ending")
    increment = getValue(name: "increment")

    whileLoop(start: start, stop: stop, increment: increment)
    doLoop(start: start, stop: stop, increment: increment)
    forLoop(start: start, stop: stop, increment: increment)
}

main()

Try It

edit

Copy and paste the code above into one of the following free online development environments or use your own Swift compiler / interpreter / IDE.

See Also

edit