Scala also has a do-while loop which works exactly like the while loop with one added difference that it executes the block of code before checking the condition. do-while ensures that the code in the curly brackets {} will execute at least once.
Syntax
The syntax is as follows.
Let’s look at a very simple example to understand the subtle difference between while and do-while.
The code below declares an immutable variable alwaysOne which is assigned a value of 1. We want to print the value of alwaysOne when it is not 1 (what a paradox!)
As the condition of a != 1 can never be true, the value of a should never be printed. But that’s not the case. Let’s run the same code using while and do-while and see what happens.
xxxxxxxxxx
val alwaysOne = 1
while (alwaysOne != 1) {
println(s"Using while: $alwaysOne")
}
xxxxxxxxxx
public class DoWhileLoop : MonoBehaviour
{
void Start()
{ // Difference is that it will run one time before is read
bool shouldContinue = false;
do
{
print ("Hello World");
}while(shouldContinue == true);
}
}
xxxxxxxxxx
The dowhile statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
xxxxxxxxxx
The dowhile statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
xxxxxxxxxx
<?php
$num=1;
do{
$num++;
echo"The number is ".$num."<br>";
}
while($num<=5);
//======output=====
/*
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6
*/
?>