Scala Programming: Find a missing number in an array of integers
Scala Programming Array Exercise-22 with Solution
Write a Scala program to find a missing number in an array of integers.
Sample Solution:
Scala Code:
object scala_basic {
def test(total_num: Int, numbers: Array[Int]) : Int = {
var total_num = 0;
total_num = 7;
var expected_num_sum = total_num * ((total_num + 1) / 2);
var num_sum = 0;
for (i <- 0 to numbers.length-1){
num_sum = num_sum + numbers(i);
}
(expected_num_sum - (num_sum));
}
def main(args: Array[String]): Unit = {
var nums1 = Array(1,2,3,4,6,7)
var array_total_nums = 7
println("Original array:")
for ( x <- nums1) {
print(s"${x}, ")
}
println(s"\nTotal number in the array: ${array_total_nums}")
println("\nMissing number of the said array:")
println(test(array_total_nums, nums1));
array_total_nums = 8
var nums2 = Array(1,2,3,4,5,6,7)
println("Original array:")
for ( x <- nums2) {
print(s"${x}, ")
}
println(s"\nTotal number in the array: ${array_total_nums}")
println("\nMissing number of the said array:")
println(test(array_total_nums, nums2));
}
}
Sample Output:
Original array: 1, 2, 3, 4, 6, 7, Total number in the array: 7 Missing number of the said array: 5 Orginal array: 1, 2, 3, 4, 5, 6, 7, Total number in the array: 8 Missing number of the said array: 0
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to test the equality of two arrays.
Next: Write a Scala program to find the number of even and odd integers in a given array of integers.What is the difficulty level of this exercise?
- New Content published on w3resource:
- 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
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework