w3resource

Scala Programming: Reverse a given list

Scala Programming List Exercise-16 with Solution

Write a Scala program to reverse a given list.

Sample Solution:

Scala Code:

object Scala_List {  
  
    
   def main(args: Array[String]): Unit = {
     val nums = List(1,2,3,4,5,6,7,8,9,10)
     println("Original List")
     println(nums)
     println("Reversed the said list:")
     println("Using reverse() function:")
     println(nums.reverse)
     println("Using for loop:")
     for(n<-nums.reverse)  
        {  
          print(n)  
          print(" ")
        }  
     }
}

Sample Output:

Original List
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
Reversed the said list:
Using reverse() function:
List(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
Using for loop:
10 9 8 7 6 5 4 3 2 1 

Scala Code Editor :

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

Previous: Write a Scala program to find an element from the last position of a given list.
Next: Write a Scala program to check a given list is a palindrome or not.

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://w3resource.com/scala-exercises/list/scala-list-exercise-16.php