Scala Tuple: Create a tuple with squares of numbers
Scala Tuple Exercise-3 with Solution
Write a Scala program that creates a tuple with the square of numbers from 1 to 6.
Sample Solution:
Scala Code:
object TupleSquareExample {
def main(args: Array[String]): Unit = {
// Create a tuple with the square of numbers from 1 to 6
val tuple = (1 to 6).map(num => num * num).toList
// Print the tuple
println("Tuple with squares: " + tuple)
}
}
Sample Output:
Tuple with squares: List(1, 4, 9, 16, 25, 36)
Explanation:
In the above exercise -
We use the map method on the range (1 to 6) to calculate the square of each number. The map method applies the provided function (num => num * num) to each element of the range and returns it as a collection.
By using toList, we convert the resulting collection into a list and assign it to the tuple.
Finally, we print the tuple using println.
Scala Code Editor :
Previous: Check if a tuple is empty or not.
Next: Create a tuple from two lists.
What is the difficulty level of this exercise?
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/tuple/scala-tuple-exercise-3.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics