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:
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?
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework