If the current number is a prime number, we print the current number. If the number is divisible by any number in the range 2 to number-1, it is not a prime number. And the inner loop checks if the current number is a prime number or not. Suppose we have a list over in Scala which we want to iterate over and do the general operations over all the elements, for this Scala came up with ForEach method. With the help of loops over we can iterate over the elements are perform the operations needed. The outer loop should iterate over the numbers in the range. Looping is an important concept in any programming languages be it Scala, java,etc. Examples Use a nested for loop to find the prime numbers from 2 to 100įirst, let's see how we can use a nested loop to find prime numbers from 2 to 100. To and until are methods that return an enumeration of numbers. For example, given a sequence of integers: scala> val nums Seq ( 1, 2, 3 ) nums: Seq Int List ( 1, 2, 3 ) scala> for (n <- nums) println (n) 1 2 3. With a for-loop we can also use the 'until' keyword. In its most simple use, a Scala for loop can be used to iterate over the elements in a collection. for (i <- 0 to 5) println (i) Output 0 1 2 3 4 5 For until. It offer the ability to iterate over a collection. But the thing is that I only want to continue to. A For Comprehension is a very powerful control structure of Scala language. Then we will iterate set elements using the for loop and print them on the console screen. I have a list of items and for each item I want to execute a future. If you observe the above output, you can notice that the above output is in form of a 2-D matrix, hence the nested for loops can be used to iterate over 2-D matrices. Scala program that uses for-to loop // Use a for-to loop to iterate over a range of numbers. Here, we are going to learn how to iterate set elements using the for loop in Scala programming language Submitted by Nidhi, on JProblem Solution: Here, we will create a set of integer numbers using the Set collection class. While the "Value of y: " statement is printed 5*5 = 25 times. Value of y: 5, Value of y: 6, Value of y: 7, Value of y: 8, Value of y: 9,Īs you can see in the above output, the "Value of x: " statement is printed 5 times.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |