w3resource

Scala Programming: Find the nth element of a given list

Scala Programming List Exercise-14 with Solution

Write a Scala program to find the nth element of a given list.

Sample Solution:

Scala Code:

object Scala_List {
  def  Nth_num[A](nums: List[A], n: Int ): A = {
    if (n < 0) throw new IllegalArgumentException("Nth position is less than 1!")
    if (n > nums.length) throw new NoSuchElementException("Nth position greater than list length!")
    nums(n)
   } 
     
   def main(args: Array[String]): Unit = {
         val nums = List(10, 20, 30, 40, 50, 70, 90, 110, 140, 120, 160)
         println("Original list:")
         println(nums)
         println("3rd element of the said element: " + Nth_num(nums, 2));
         println("6th element of the said element: " + Nth_num(nums, 5));
         println("1st element of the said element: " + Nth_num(nums, 0));
         }
}

Sample Output:

Original list:
List(10, 20, 30, 40, 50, 70, 90, 110, 140, 120, 160)
3rd element of the said element: 30
6th element of the said element: 70
1st element of the said element: 10

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to find the even and odd numbers from a given list.
Next: Write a Scala program to find an element from the last position of a given list.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.