Swift Array Programming Exercises: Compute the sum of the first 2 elements of a given array of integers. Return 0 if the length of the given array is 0 and return the first element value If the array length is less than 2
Write a Swift program to compute the sum of the first 2 elements of a given array of integers. Return 0 if the length of the given array is 0 and return the first element value If the array length is less than 2.
Pictorial Presentation:
Sample Solution:
Swift Code:
func array_sum2(_ a: [Int]) -> Int {
let size = a.count
if size>1
{
return a[0] + a[1]
}
else
{
return a[0]
}
}
print(array_sum2([1, 2, 3]))
print(array_sum2([1, 1]))
print(array_sum2([10]))
Sample Output:
3 2 10
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to find the larger value of a given array of integers and set all the other elements with that value. Return the changed array.
Next: Write a Swift program to create a new array of length 2 containing the middle elements from two give array of integers and length 3.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics