roll a die 20 times and sun the values in swift

main.swift
var sum = 0 // initialize sum to 0
for _ in 1...20 {
    let roll = Int.random(in: 1...6) // generate a random number between 1 and 6
    sum += roll // add the roll to the sum
    print("Roll: \(roll)") // print the roll for each iteration
}
print("Total sum: \(sum)") // print the total sum after all rolls are done
318 chars
8 lines

In the code above, we first initialize the sum to 0. Then, we use a for loop to generate a random number between 1 and 6 for 20 times, adding each roll to the sum. We also print the roll for each iteration. Finally, we print the total sum after all rolls are done.

related categories

gistlibby LogSnag