Scala program to demonstrate the nested while and do-while loop

Here, we are going to demonstrate the nested while and do-while loop in Scala programming language.
Submitted by Nidhi, on May 06, 2021 [Last updated : March 09, 2023]

Scala – Nested While and Do-while Loops

Here, we will demonstrate the nested while and do-while loop. We will print a table of numbers 2 to 5 using nested while and do-while loop.

Scala code to demonstrate the example of nested while and do-while loops

The source code to demonstrate the nested 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 defined main() function. The main() function is the entry point for the program.

Nested while loop

// Scala program to demonstrate the 
// nested "while" loop

object Sample {  
    def main(args: Array[String]) {  
        var cnt1:Int=0;
        var cnt2:Int=0;
        
        cnt1=2;
        while(cnt1<=5)
        {
            cnt2=1;
            while(cnt2<=10)
            {
                printf("%d ",(cnt1*cnt2));
                cnt2=cnt2+1;
            }
            cnt1=cnt1+1;
            println();
        }
    }
}  

Output

2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 

Explanation

Here, we created two integer variables cnt1, cnt2 initialized with 0. cnt1 is used as counter for outer loop and cnt2 is used for inner loop. The outer loop executes from 2 to 5 and the inner loop will execute 10 times for each number of the outer loop to print the table on numbers on the console screen.

Nested do-while loop

// Scala program to demonstrate the 
// nested "do-while" loop

object Sample {  
    def main(args: Array[String]) {  
        var cnt1:Int=0;
        var cnt2:Int=0;
        
        cnt1=2;
        do
        {
            cnt2=1;
            do
            {
                printf("%d ",(cnt1*cnt2));
                cnt2=cnt2+1;
            }while(cnt2<=10)
            
            cnt1=cnt1+1;
            println();
        }while(cnt1<=5)
    }
}  

Output

2 4 6 8 10 12 14 16 18 20 
3 6 9 12 15 18 21 24 27 30 
4 8 12 16 20 24 28 32 36 40 
5 10 15 20 25 30 35 40 45 50 

Explanation

Here, we created two integer variables cnt1, cnt2 initialized with 0. cnt1 is used as counter for outer loop and cnt2 is used for inner loop. The outer loop executes from 2 to 5 and the inner loop will execute 10 times for each number of the outer loop to print the table on numbers on the console screen.

Scala Looping Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.