Q:

Rust program to demonstrate the break statement with while and for loops

belongs to collection: Rust Looping Programs

0

In this program, we will use the break statement with while and for loop to terminate the loop when the given if statement is true.

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 while and for loop is given below. The given program is compiled and executed successfully.

// Rust program to demonstrate the 
// break statement with "while" and "for" loops

fn main() {
    let mut cnt:i32 = 1;
    
    while cnt<=10
    {
        print!("{} ",cnt);
        if cnt==5
        {
            break;
        }
        cnt=cnt+1;
    }
    
    println!();
    
    for cnt in 1..11
    {
        print!("{} ",cnt);
        if cnt==5
        {
            break;
        }
    }    
}

Output:

1 2 3 4 5 
1 2 3 4 5 

Explanation:

Here, we used the break statement with while and for loop to terminate the loop when the value of the cnt variable is equal to 5.

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

total answers (1)

Rust program to demonstrate the break statement wi... >>
<< Rust program to demonstrate the nested for loop...