...

/

Indefinite Loop - While and Loop

Indefinite Loop - While and Loop

This lesson will discuss two indefinite loop: While and Loop.

While loop

While loop also iterates until a specific condition is reached. However, in the case of a while loop, the number of iterations is not known in advance.

Syntax

The while keyword is followed by a condition that must be true for the loop to continue iterating and then begins the body of the loop.

The general syntax is :

Example

The following example makes use of a while loop to print a variable value. The loop terminates when the variable’s value modulus 2 equals 1.

Press + to interact
fn main() {
let mut var = 1; //define an integer variable
let mut found = false; // define a boolean variable
// define a while loop
while !found {
var=var+1;
//print the variable
println!("{}", var);
// if the modulus of variable is 1 then found is equal to true
if var % 2 == 1 {
found = true;
}
println!("Loop runs");
}
}

Explanation

  • A mutable variable, var, is defined on line 2.
  • A mutable
...