For Loop :
Syntax :
for (condition) {//-- Code to Run//-- Code to Run}
Rule :
1. Check condition
2. If condition is True then run code withing for loop else exit
Example:
scala> val hadoopguru = Range(1, 10)
hadoopguru: scala.collection.immutable.Range = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> for (h <- hadoopguru) {
| println(s"Item : ${h}")
| }
Item : 1
Item : 2
Item : 3
Item : 4
Item : 5
Item : 6
Item : 7
Item : 8
Item : 9
While Loop :
Syntax :
while (condition) {//-- Code to Run//-- Code to Run}
Rule :
1. Check condition
2. If condition is True then run code within while loop else if condition is False then exit
Example:
scala> var h = 0h: Int = 0scala> while (h < 10) {| h = h+1| println(s"Item : ${h}")| }Item : 1Item : 2Item : 3Item : 4Item : 5Item : 6Item : 7Item : 8Item : 9Item : 10
Note : While loop continue to run until condition is True. Be careful not to get into infinite loop.
do while Loop :
Syntax :
do {//-- Code to Run//-- Code to Run} while (condition);
Rule :
1. Run code at least once then Check condition
2. If condition is True then run code within while loop again else if condition is False then exit
Example:
scala> var h = 0h: Int = 0scala> do {| h = h+1| println(s"Item : ${h}")| } while (h < 0);Item : 1
Note : do While loop is similar to while loop except code block runs at least once.
keywords : loops in scala, for loop, while loop, do while loop, scala interview questions, scala tutorial, scala vs python, learn scala, infinite loop.
No comments:
Post a Comment