Table of content

Control Flow

Control flow in programming means, which path the program execution follows. This is based on different decisions when a particular decision is fulfilled, then certain blocks of codes get executed.

The decision can be checked using a small keyword if .

Let us consider the program below:

fn main() {
    let number = 3;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}

Here, in the above program, we declared a variable number and assigned it with a value 3. In the next line, the condition is checked using if number < 5. Now if the condition is checked as true, the first block is executed or else the second block is executed.

This is an example of a single decision statement.

Handling multiple decisions

We can set multiple conditions, with the help of the keyword else-if. Consider the program below:

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}

In the above program, the variable number is assigned a value 6. Now, in the first if condition, it is checked whether the number is divisible by 4.

Now when the next condition has to be checked, then the keyword else if is required and subsequently for all other condition, except the last one. If none of the condition is fulfilled, then the else in the last gets executed.

Using if in a let state

ment

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions