w3resource

Swift Basic Programming Exercise: Count the number of times that two 7's are next to each other in a given array of integers

Swift Basic Programming: Exercise-27 with Solution

Write a Swift program to count the number of times that two 7's are next to each other in a given array of integers.

Pictorial Presentation:

Swift Basic Programming Exercise: Count the number of times that two 7's are next to each other in a given array of integers.

Sample Solution:

Swift Code:

func array77(_ input: [Int]) -> Int {
    var ctr = 0
        for (index, number) in input.enumerated() {
        let nextIndex = index + 1
        
        if nextIndex < input.endIndex && number == 7 && (input[nextIndex] == 7 ) 
        {
            ctr += 1
        }
    }
    return ctr
}

print(array77([7, 7, 3]))
print(array77([7, 7, 2, 7, 7]))
print(array77([7, 5, 2, 7]))

Sample Output:

1
2
0

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to create a string taking characters at indexes 0, 2, 4, 6, 8, .. from a given string.
Next: Write a Swift program to test whether a value presents sequentially three times in an array of integers or not.

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://w3resource.com/swift-programming-exercises/basic/swift-basic-exercise-27.php