roll a die x times and sun the values in swift

main.swift
let rolls = 10 // number of times to roll the die
var sum = 0 // initialize sum to 0
var results = [Int]() // create an empty array to store results

// loop through the rolls and append a random number between 1 and 6 to the results array
for _ in 1...rolls {
    let roll = Int.random(in: 1...6)
    results.append(roll)
}

// loop through the results array and add each number to the sum variable
for result in results {
    sum += result
}

print("Results: \(results)") // print the results array
print("Sum: \(sum)") // print the sum of the results
554 chars
18 lines

In this code, we first set the number of times we want to roll the die in the rolls constant. The sum is initialized as 0 and an empty array results is created to store the individual rolls.

We then loop through the rolls and generate a random number between 1 and 6 using the built-in random(in:) function in Swift. Each result is appended to the results array.

Finally, we loop through the results array, add each number to the sum variable, and print the results array and the sum.

gistlibby LogSnag