Q:

Scala program to demonstrate the break statement in while and do-while loop

belongs to collection: Scala Looping Programs

0

Here, we will demonstrate the break statement in the while and do-while loop to terminate the loop during its execution based on the specific condition.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the break statement in the while and do-while loop is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

In the all below program, we used an object-oriented approach to create the program. We created an object Sample. We imported the scala.util.control.Breaks._ package to use the break statement.

break statement with while loop

// Scala program to demonstrate "break" statement 
// in "while" loop

// Importing  package 
import scala.util.control.Breaks._
object Sample {  
    def main(args: Array[String]) {  
        var cnt:Int=0;
        
        cnt=1;
        breakable 
        {
            while(cnt<=5)
            {
                printf("%d ",cnt);
                cnt=cnt+1;
                
                if(cnt==3)
                    break;
            }
        }
        println();
    }
} 

Output:

1 2 

Explanation:

Here, we created an integer variable cnt initialized with 0. We created a breakable block to use the break statement.

In the while loop, we print the value of the cnt variable. We terminate the loop using the break statement when the value of the cnt variable reaches 3.

break statement with do-while loop

// Scala program to demonstrate "break" statement 
// in "do-while" loop

// Importing  package 
import scala.util.control.Breaks._

object Sample {  
    def main(args: Array[String]) {  
        var cnt:Int=0;
        
        cnt=1;
        breakable 
        {
            do
            {
                printf("%d ",cnt);
                cnt=cnt+1;
                
                if(cnt==3)
                    break;
            }while(cnt<=5)
        }
        println();
    }
}  

Output:

1 2 

Explanation:

Here, we created an integer variable cnt initialized with 0. We created a breakable block to use the break statement.

In the do-while loop, we print the value of the cnt variable. We terminate the loop using the break statement when the value of the cnt variable reaches 3.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to execute do-while loop at least 1 ... >>
<< Scala program to demonstrate the nested while and ...