Q:

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

belongs to collection: Scala Looping Programs

0

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.

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 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 cnt1cnt2 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)
    }
}  

Explanation:

Here, we created two integer variables cnt1cnt2 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.

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 

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

total answers (1)

Scala program to demonstrate the break statement i... >>
<< Scala program to implement infinite loop using whi...