Skip to content

Latest commit

Β 

History

History

if-else-statements

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Β 
Β 

Table of ContentsπŸ“š

if else statements

comparison operators

The comparison operators are used to compare two values.

Operator Description
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

if

Imagine that you are a programmer and you have to write a program that will tell if the value of a variable is positive

let x = 5;

For that, you will have to check if x is superior to 0.

We can do that with the if statement.

if x > 0 {
    println!("x is positive πŸ‘");
}

The code between the {} will be executed because the condition x > 0 is true.

If we change the value of x to a negative number, the code between the {} will not be executed.

else

Imagine that you are a programmer and you have to write a program that will say hello if the value of a variable is equal to 5, and goodbye if it is not.

To do that, you will first have to check if x is equal to 5, and then use the else statement to say goodbye if the condition is not true.

if x == 5 {
    println!("Hello πŸ‘‹");
} else {
    println!("Goodbye πŸ«‚");
}

Let's run the code with x = 5:

Hello πŸ‘‹

And with x = 6:

Goodbye πŸ«‚

else if

It is possible to have more than one condition to be checked.

Imagine that we want to say hello if x is equal to 5, good morning if it is equal to 6, and good night if either of the two conditions is not true.

we can do that with the else if statement.

if x == 5 {
    println!("Hello πŸ‘‹");
} else if x == 6 {
    println!("Good morning πŸŒ…");
} else {
    println!("Good night πŸ›Œ");
}

lets run the code with x = 5:

Hello πŸ‘‹

And with x = 6:

Good morning πŸŒ…

And with x = 7:

Good night πŸ›Œ

ℹ️ We can put as many else if as we want. The condition of the else if will be checked after the condition of the previous else if.


Home 🏠 - Next Section ⏭️


Course created by SkwalExe and inspired by Dcode