Javatpoint Logo
Javatpoint Logo

While loop

The 'while-loop' is a conditional loop. When a program needs to evaluate a condition then the conditional loop is used. When the condition is true then it executes the loop otherwise it terminates the loop.

Syntax of 'while loop'

  • In the above syntax, while loop evaluates the condition. If the condition is true, block statements are executed otherwise it terminates the loop. Rust provides this inbuilt construct which can be used in combinations with 'loop', 'if', 'else' or 'break' statement.

Flow diagram of while loop


Rust While loop

Let's see a simple example

Output:

1 2 3 4 5 6 7 8 9 10

In the above example, 'i' is a mutable variable means that the value of 'i' can be modified. The while loop executes till the value of 'i' is less than 10 or equal to 10.

Let's see a simple example

Output:

10 20 30 40 50 60

In the above example, the elements of an array has been iterated using while loop.

Disadvantages of while loop:

  • While loop can cause the problem if the index length is incorrect.
  • It is also slow as the compiler adds the runtime code to perform the conditional check on every iteration through this loop.

Next TopicRust For Loop




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials