w3resource

Swift Array Programming Exercises: Compute the sum of the numbers of a given array of integers except the number immediately after a 11

Swift Array Programming: Exercise-26 with Solution

Write a Swift program to compute the sum of the numbers of a given array of integers except the number immediately after a 11.

Pictorial Presentation:

Swift Array Programming Exercises: Compute the sum of the numbers of a given array of integers except the number immediately after a 11

Sample Solution:

Swift Code:

func sum_11(array_nums: [Int]) -> Int {
    var sum = 0
    var ans = true
    for x in 0..<array_nums.count
    {
        if array_nums[x] != 11 && ans == true {
            sum += array_nums[x]
            ans = true
        
        }
        else
        {
        ans = false
        }
       
    }
    
    return sum
}

print(sum_11(array_nums: [1, 2, 11, 1])) 
print(sum_11(array_nums: [1, 1])) 
print(sum_11(array_nums: [1, 2, 2, 1, 11, 5]))
print(sum_11(array_nums: [1, 2, 2, 1, 11]))  
 

Sample Output:

3
2
6
6

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to find the difference between the largest and smallest values in a given array of integers and length 1 or more.
Next: Write a Swift program to check if a given array of integers contains a 3 next to a 3 somewhere.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/swift-programming-exercises/array/swift-array-exercise-26.php