Q:

Rust program to demonstrate the break statement with a nested loop

0

In this program, we will use the break statement with nested while loop. If we use the break statement inside the inner loop then it terminates the only inner 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 break statement with the nested loop is given below. The given program is compiled and executed successfully.

// Rust program to demonstrate the 
// break statement with nested loop

fn main() {
    let mut cnt1:i32 = 1;
    let mut cnt2:i32 = 0;
    
    while cnt1<=5
    {
        cnt2=1;
        while cnt2<=10
        {
            print!("{} ",cnt1);
            
            if(cnt2 == 5)
            {
                break;
            }
            cnt2 = cnt2 + 1;
        }
        cnt1=cnt1+1;
        println!();
    }
}

Output:

1 1 1 1 1 
2 2 2 2 2 
3 3 3 3 3 
4 4 4 4 4 
5 5 5 5 5 

Explanation:

Here, we used the break statement inside the inner loop. In the case of a nested loop, if we use the break statement nested loop inside the inner loop then it terminates the inner loop.

In our program, the normally inner loop executes 10 times but it will execute only 5 times because of the break statement.

Rust Looping Programs »

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now