w3resource

Swift Basic Programming Exercise: Compute the sum of the two integers

Swift Basic Programming: Exercise-1 with Solution

Write a Swift program to compute the sum of the two integers. If the values are equal return the triple their sum.

Pictorial Presentation:

Swift Basic Programming Exercise: Compute the sum of the two integers.

Sample Solution:

Swift Code:

func triple_sum(a: Int, b: Int) -> Int {
    if a == b 
     {
        return (a + b) * 3
     }
     else 
     {
        return a + b
     }
 }

print(triple_sum(a: 1, b: 2))   
print(triple_sum(a: 3, b: 2)) 
print(triple_sum(a: 2, b: 2))

Sample Output:

3
5
12

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Swift Basic Exercises.
Next: Write a Swift program to compute and return the absolute difference of n and 51, if n is over 51 return double the absolute difference.

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-1.php