Control Flow

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

control-flow

There can be different ways through which the program control can flow. They are:

  • Sequential: Sequential flow is the way when the program execution statement goes serially, without any conditions be checked. (When the loops or conditions are not there, the program takes a sequential flow)
  • Conditional: Conditional flow means the program execution path depends on decisions. There can be a decisional statement, which will check for true or false and redirect the program as per the outcome.
  • Loop: Loop means to iterate or execute a block of code again and again till the termination point is reached. There can be different types of loops, we shall discuss in detail.

Conditional Flow

In the conditional flow, the control flow of the program depends on a particular decision. In case the decision is true, the program execution takes a path otherwise when the decision is false, then the program execution takes a different path.

rust-contional-flow03

As shown in the figure above, the program flow enters the decisional block and then if the condition is TRUE then the program control enters the left block, and if the condition is FALSE, then the program control enters the right block of statements.

IF Conditions

  • A decisional statement is written followed the keyword if.
  • The first open brace { marks the starting of the scope of the if , and the closing brace } marks the end of the if scope.
  • The else part also contains its open brace { and closing brace } , which marks the start and end of its scope.

There can be four different types of if statement. They are as below:

if

Using the if statement, the condition is checked and if the condition is true, then the code inside the if block gets executed.

The Syntax for if:

if decision_check_statement
{
       //code
}

Below example demonstrate whether a person can vote or not, based on the Age, using if statement in Rust:

fn main() {
 let age = 50;
 if age > 18 {
  println!("You are eligible to cast vote");
 }
}
simple-if

combining multiple conditions if

Nested if Conditions:

There can also be if condition, inside another if. In such cases, it is called nested if. Nested if is required when we have to check more then one decision to check and conclude a result or run a block of code.

Syntax:

if decisonal_expression {
 if decisional_expression1 {
  //code
 }
}

Program to check whether a number is odd and divisible by 3.

fn main() {
 let number = 5;
 if number % 2 == 1 {
  if number % 3 == 0 {
   println!("Odd and divisible by 3");
  }
 }
}

The variable number is assigned with an integer 5. The first if checks whether the number is an odd number using the decision if number % 2 == 1. And when the decision is true, then the program flows to the second if to check the next decision, whether the number is divisible by 3, using number% 3 == 0.

In our case, the number is 5. Therefore, the first condition is satisfied, but the next condition is not satisfied, resulting in the program flow to go out of the if scope and print nothing.

Output :

nested-if

Let us now see the case, when both the if decisions become true.

fn main() {
 let number = 6;
 if number % 2 == 1 {
  if number % 3 == 0 {
   println!("Odd and divisible by 3");
  }
 }
}

In this program we have assigned the number to 9. Now the first condition(whether odd) is true. And also, the second condition (whether divisible by 3) is true. Therefore, the code inside the nested if(second if) gets executed.

Output :

nested-if-true

if else

Using the if statement, the condition is checked and if the condition is true, then the code inside the if block gets executed. In case, the result in the condition becomes false, then the else block gets executed.

The syntax for if-else in Rust:

if decision_check_statement
{
    //code
}
else 
{
   //code
}

Example Program: (When the decision returns true) if check_value > 100

fn main() {
  let check_value = 200;
  if check_value < 100 {
   println!("The decision returns true !");
  }
  else {
   println!("The decision returns false !");
  }
}

In the above program, if check_value <100 is the decisional statement. And if the decision returns true, then the code inside the if block gets executed. And when the decision returns false, then the code inside the else block gets executed.

Program Output :

if-true

As we have seen in the program output, since the decision is checked and is found true, and thus only the if part has been executed and the else part is not executed. This way the program flow depends on the decision.

Example Program : (When the decision returns false) if check_value < 100

fn main()
{
	let check_value= 200;
	if check_value < 100
{
	println!("The decision returns true !");
}
else
{
	println!("The decision returns false!");
	
}
}

Program Output :

if-false

Nested else:

There can be else block inside another else block. This way of using else is called nested else.

Syntax :



if..else-if

Sometimes we want to take a decision in else block as well when we have more than one options, In such cases, we can use if..else..if block.

add................................

if ..else if..else (Handling Multiple Decisions) :

There could be a situation where the first decision leads to false but we might need to verify the decision again based on the first decision. So, in such cases, we might need to check the condition on the else block. In such, cases we can if-else...if else.

Multiple decisions Syntax:

if decision_statement_1
{
	//statements
}
else if decision_statement_2
{
	//statements
}
else 
{
	//statement
}

The first decision is taken in if. When the condition is false in the if block, then else block is executed. We have one more decision to take in the else block. So, that is why, we have used if block along with else block. We can have as many as else-if blocks required.

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");
    }
}

Program Output :

multiple-decisions

Note: Once the condition divisible by 3 is reached, the execution stopped there and did not check for divisibility by 2 , which could also, in turn, return true.

Loops in Rust(Iterative Flow)

Loop is a single or a set statements which gets executed repeatedly until and unless a certain condition is reached which will terminate the loop.

Loop is also called an iteration because a set of similar statements gets executed again and again. Loops can be broadly classified as:

  • Finite Loop : A finite loop is that, which can be terminated when a particular condition is reached or turns true.
  • Infinite Loop: An infinite loop will keep on iterating since it has no termination point. Therefore, infinite loop can only be stopped by killing the process or the thread. In our article, we are not concerned about infinite loops.

Pictorial Representation of a LOOP :

simple-loop

Loops can be classified into three different types. They are:

  • For Loop
  • While Loop
  • Do-while Loop

For Loop:

A for Loop, is used to execute a block of code multiple times.

In the For Loop for keyword indicates the for-loop, followed by the variable_name and the keyword in, and then writing the expression.

The scope of the for-loop will start with an opening brace { and ends with a closing brace }. And inside these brackets, resides the code which we want to get executed repeatedly.

An expression is nothing, but a limit which indicates where the loops start and where it ends.

Syntax :

for variable_name in expression {
        //some code
}

Program to print a line using for loop :

fn main()
{
for counter in 0..10 {
    println!("{}", counter);
}
}

In the above program, inside the main() function, we have declared a for-loop using the keyword for. counter is the loop variable, and in is the keyword required. 0..10 is the expression indicating that the variable value starts with 0 and ends with 10.

Program Output :

for-loop

In the above output, we have seen that the counter value starts with 0 and increments up to 9 till the loop ends. (counter value = 10, is the termination condition for the loop, as it is mentioned has the higher limit in the expression).

The value of the counter value is printed since we used the macro println!() to print the value of the variable.

For Loop (Using Continue):

A for loop can be used using the keyword continue. This is used when the loop has to be continued only just skipping the iteration for which the if condition satisfies.

This is done by writing the continue; statement after the conditional expression of if.

Syntax :

for variable_name in limit {
    if  condition expression { continue; }
    //code
}

Program :

fn main()
{
for value in 0..10 {
    if value % 2 == 0 { continue; }

    println!("{}", value);
}
}

Program Output :

for-continue

In the above, program output all the value is printed between 0 to 10 except the values which are divisible by 2. That is, the expression value % 2 == 0 checks for the divisibility and the next expression {continue;} skips the loop iteration for which the value is divisible by 2.

In this way, we can skip particular iterations, but still, the loop will continue up to its higher limit.

While Loop:

while loops are used when the user is not sure, about how many times the loop should get executed or how many time the iteration should go on.

The while loop, should be followed with a boolean variable(which can be either false or true), and there should be an if condition which must stop the while iteration.

Conditions for while:
  • While loop starts with the keyword while followed by a boolean type variable.
  • An open brace { starts the scope of the while, and the code which needs to be iterated and written inside, and the scope ends with a closing brace }.
  • if statement checks for the condition, and change the boolean variable into true or false which will stop the loop.

Syntax :

while boolean_variable
{
      //some code
if condition expression
{
      boolean_variable = true or false
}
}

Program :

fn main()
{
	let mut value = 5; // mut x: i32
	let mut bool_variable = false; // mut done: bool

while !bool_variable {
    value=value + 3;

    println!("{}", value);

if value % 5 == 0 {
        bool_variable = true;
    }
}
}

In this above example, we have declared a variable value which is muted, that is can be updated later in the program. Then the boolean type variable bool_variable is set to false, which is also muted, for it has to be changed to true later in the program.

Then the scope of while starts with the while keyword followed by the boolean variable, which is set to false. Inside the scope of the while, the codes are written which need to gets executed. In our case, we are incrementing the value of the variable value by 3 and then printing the value after each increment.

Then we have the if statement which checks for the condition, whether the value is divisible by 5. If the condition turns out to be TRUE, then the bool_variable inside the if, is set to TRUE and the loop is terminated.

Program Output:

while-loop

20, the last value is printed, which should not have been printed, since it is divisible by 5 and so turns the bool_variable into TRUE. But, it is printed, it is so because the print statement is earlier of the if statement.

Loop (using break):

The while loop can be terminated only when the if condition returns a TRUE or FALSE and the boolean variable is changed.

We can also set a loop, where there is no need to use the boolean variable. And only using a keyword break, the loop can be terminated.

Syntax :

loop {
     // code
}
     if conditional_expression { break; }
}

Program :

let mut value = 5;

loop {
    value= value+3;

    println!("The value is {}", value);

    if value % 5 == 0 { break; }
}

In the above program, loop is the keyword to start the scope of the Loop. Inside the loop we have a statement value= value + 3 which increments the value by 3 each time the code is iterated by the loop.

Then we use the macro println!() to print the value of value each time the loop gets iterated. After the if followed by the conditional expression, we have used break; to stop the iteration.

Program Output :

loop-break

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions