Scala supports “while” and “do/while” loops, which repeat a statement until a Boolean expression returns false.
Scala while loop
The while loop executes a block of code as long as a condition is true.
Syntax of while Loop
while (<Boolean expression>) {statements}
while loop example
Here is an example of a while loop that prints 10 to 1 in descending order :
var x = 10; while(x > 0){ println(x); x-=1; }
Output:
10
9
8
7
6
5
4
3
2
1
Scala do while Loop
The do-while checks to see if the condition is true after running the block.
Syntax of do while Loop
do {statements} while (<Boolean expression>)
do while loop example
Lets rewrite the code to print 10 to 1 using do..while loop :
var x = 10; do{ println(x); x-=1; }while(x>0)
Output:
10
9
8
7
6
5
4
3
2
1
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post