Swift Array Programming Exercises: Count the number of even integers in the given array
Swift Array Programming: Exercise-24 with Solution
Write a Swift program to count the number of even integers in the given array.
Pictorial Presentation:
Sample Solution:
Swift Code:
func countEvens(a: [Int]) -> Int {
var ctr = 0
for x in 0..<a.count {
if a[x] % 2 == 0 {
ctr += 1
}
}
return ctr
}
print(countEvens(a: [1, 2, 3, 4, 5]))
print(countEvens(a: [1, 3, 5, 7]))
print(countEvens(a: [2, 4, 6, 8]))
Sample Output:
2 0 4
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to create a new array taking the first element from two given arrays of integers. If either array is length 0, ignore that array.
Next: 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.
What is the difficulty level of this exercise?
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/array/swift-array-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics