Programming Fundamentals/Arrays/Swift

arrays.swift

edit
// This program uses arrays to display temperature conversion tables 
// and temperature as an array subscript to find a given conversion.
//
// References:
//     https://www.mathsisfun.com/temperature-conversion.html
//     https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html

import Foundation

func buildC(size: Int) -> [Double]
{
    var c = [Double]()
    var value: Double
    
    for index in 0...size
    {
        value = Double(index * 9) / 5 + 32
        c.append(value)
    }
    
    return c
}

func buildF(size: Int) -> [Double]
{
    var f = [Double]()
    var value: Double
    
    for index in 0...size 
    {
        value = Double((index - 32) * 5) / 9
        f.append(value)
    }
    
    return f
}

func displayArray(name: String, array: inout [Double]) 
{
    for index in 0...array.count - 1
    {
        print(name + "[" + String(index) + "] = " + String(array[index]))
    }
}

func findTemperature(c: inout [Double], f: inout [Double]) 
{
    var temp: Int
    var size: Int
    
    size = minimum(value1:c.count, value2:f.count)
    repeat 
    {
        print("Enter a temperature between 0 and " + String((size - 1)))
        temp = Int(readLine(strippingNewline: true)!)!
    } while temp < 0 || temp > size - 1
    print(String(temp) + "° Celsius is " + String(c[temp]) + "° Fahrenheit")
    print(String(temp) + "° Fahrenheit is " + String(f[temp]) + "° Celsius")
}

func minimum(value1: Int, value2: Int) -> Int 
{
    var result: Int
    
    if value1 < value2
    {
        result = value1
    }
    else
    {
        result = value2
    }
    
    return result
}

func main()
{
    var c = buildC(size:100)
    var f = buildF(size:212)
    displayArray(name:"C", array:&c)
    displayArray(name:"F", array:&f)
    findTemperature(c:&c, f:&f)
}

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