Programming Fundamentals/Loop Examples Swift

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Counting[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()

Output[edit]

Enter starting value:
1
Enter ending value:
3
Enter increment value:
1
While loop counting from 1 to 3 by 1:
1
2
3
Do loop counting from 1 to 3 by 1:
1
2
3
For loop counting from 1 to 3 by 1:
1
2
3

References[edit]