w3resource

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(numbers: Array[Int]): Int = {
    var total_num = 0;
    total_num = numbers.length;
    var expected_num_sum = 0
    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);
    }
    (num_sum - expected_num_sum);
  }
  def main(args: Array[String]): Unit = {
    var nums1 = Array(1, 2, 3, 4, 6, 7)
    println("Original array:")
    for (x <- nums1) {
      print(s"${x}, ")
    }
    println(s"\nTotal items in the array: ${nums1.length}")
    println("\nMissing number of the said array:")
    println(test(nums1))
    var nums2 = Array(1, 2, 3, 4, 5, 6, 7)
    println("Original array:")
    for (x <- nums2) {
      print(s"${x}, ")
    }
    println(s"\nTotal items in the array: ${nums2.length}")
    println("\nMissing number of the said array:")
    println(test(nums2));
  }
}

Sample Output:

Original array:
1, 2, 3, 4, 6, 7, 
Total items in the array: 6

Missing number of the said array:
5
Original array:
1, 2, 3, 4, 5, 6, 7, 
Total items in the array: 7

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?



Follow us on Facebook and Twitter for latest update.