w3resource

Swift Basic Programming Exercise: Accept two integer values and to test which value is nearest to the value 10

Swift Basic Programming: Exercise-15 with Solution

Write a Swift program that accept two integer values and to test which value is nearest to the value 10, or return 0 if both integers have same distance from 10.

Pictorial Presentation:

Swift Basic Programming Exercise: Accept two integer values and to test which value is nearest to the value 10.

Sample Solution:

Swift Code:

func close_10(_ a: Int, _ b: Int) -> Int {
    if abs(10 - b) > abs(10 - a) 
    {
        return a
    }
    else if abs(10 - b) < abs(10 - a) 
    {
        return b
    } 
    else 
    {
        return 0
    }
}
print(close_10(8, 13))
print(close_10(12, 7))
print(close_10(14, 6))

Sample Output:

8
12
0

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to find the largest number among three given integers.
Next: Write a Swift program that accept two integer values and test if they are both in the range 20..30 inclusive, or they are both in the range 30..40 inclusive.

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/basic/swift-basic-exercise-15.php