Else-If Ladder Statement

In this, there is more than 1 condition. In fact, there can be many and after that, there is else now suppose any of the conditions does not satisfy then all are ignored and block of code inside else part will be executed. But suppose if some condition is satisfied then the block of code in that part will be executed and rest will be ignored.

Syntax:

if boolean_expression1 {
//statements if the expression1 evaluates to true
} else if boolean_expression2 {
//statements if the expression2 evaluates to true
} else {
//statements if both expression1 and expression2 result to false
}

Example: To check if the number is negative, positive or zero

Rust
fn main() {
   let num = 0 ;
   if num > 0 {
      println!("num is positive");
   } else if num < 0 {
      println!("num is negative");
   } else {
      println!("num is neither positive nor negative") ;
   }
}

Output:

num is neither positive nor negative

Rust – If-else Statement

Branching with if-else in rust also is similar to other languages. Just the difference is the way of writing(syntax). Here the condition doesn’t need to be surrounded by parenthesis. Decision-making structure is an important part of life. Similarly, in programming also there are situations where you have to decide(make decisions) that for the specific conditions which code should be executed. For this, we use the if-else. 

Decision-making statements in programming languages decide the direction of the flow of program execution.

Mainly there are 4 types that are used more often are explained in this article.

They are:

  1. if statement
  2. if-else statement
  3. else-if ladder statement
  4. Nested if-else statement

Similar Reads

If Statement

Here only 1 condition is there and if that condition is true then a block of code inside the if statement will be executed....

If-Else Statement

Here also there is only 1 condition but the difference here is that there is another block of code that is executed when the if the condition is false and suppose that the condition is true then the block of code inside if is executed and else part is ignored completely....

Else-If Ladder Statement

In this, there is more than 1 condition. In fact, there can be many and after that, there is else now suppose any of the conditions does not satisfy then all are ignored and block of code inside else part will be executed. But suppose if some condition is satisfied then the block of code in that part will be executed and rest will be ignored....

Nested if-else statement

If we want to check multiple conditions we can use if statements within if statements we call it as nested statement. A nested if is an if statement that is the target of another if or else....