Rust/C2/Control-Flow-in-Rust/English

From Script | Spoken-Tutorial
Revision as of 11:06, 2 February 2021 by Pravin1389 (Talk | contribs)

Jump to: navigation, search

Title of the script: Control-Flow

Author: Jayesh Katta Ramalingaiah

Domain Reviewer:

Novice Reviewer:

Keywords: Rust, variables, if, else, else if, conditions


Visual Cue
Narration
Slide: Title Welcome to the spoken tutorial on “Control-Flow in Rust”.
Slide:

Learning Objectives

In this tutorial, we will learn about the:
  • if/else control flow statements
  • Different types of loops supported in Rust
  • Syntax of all the control flow statements and their usage
Slide: System Specifications This tutorial is recorded using:
  • Ubuntu Linux OS version 18.04
  • Rust version 1.47.0
  • Visual Studio Code version 1.45.0 (code editor)

However, you may use any other editor of your choice.

Slide : Pre-requisites To practice this tutorial,
  • You should be familiar with compiling and running Rust files.
  • If not, please go through the prerequisite Rust tutorials on this website.
Slide: Code files
  • The file used in this tutorial is available in the Code files link on this tutorial page.
  • Pls download and extract the file.
  • Make a copy and then use it for practising.
Slide: Control Flow
  • Control flow means deciding whether to run a piece of code, based on a condition.
  • This is an integral part of any programming language.
  • This can be achieved using if and else statements
Slide: Control Flow

[Highlight]: if expressions

  • if is the most common way to handle the flow of our code.
Slide: Control Flow

[Highlight]: else if

  • We can use else if, if there are multiple conditions to be evaluated.
Slide: Control Flow -1


  • We can use if without else, however else cannot be used without if.
  • else is always preceded with an if statement.
Slide: Control Flow -2
  • Also, we can use one or more else if along with the if statement.
  • Ensure that when you use else if, always follow it up with an else condition too.
  • The code works fine even when we don’t end with an else statement.
  • However, to maintain coding standards it is advised to use else condition when we are using else if

Let us understand all this by using an example.

Press Ctrl+Alt+T keys Open the terminal by pressing Ctrl,Alt and T keys simultaneously on the keyboard.


Ensure that you have root permissions to run the commands.

Only Narration Here onwards, please remember to press the Enter key after typing each command.
[Terminal] Type:


cd Desktop/MyRustProject

[Enter]

Using cd command go to the Rust practice folder which we created earlier.
[Terminal] Type:


cargo new control_flow

[Enter]

Let us create a new project named control_flow.


Type the command as shown.

Open Visual Studio Code editor. You may use any editor of your choice.


I will use Visual Studio Code editor for this demonstration.

[Editor]


Welcome Page ->

Open Folder ->

control_flow

Open the created project by clicking on the Open folder link in the Welcome page.


Browse and locate the folder “control_flow”.


Then click on the OK button at the top right corner.

[Editor]

Click on control_flow

Under the EXPLORER section, expand the project folder “control_flow” by clicking on it.
[Editor] Expand src and click on main.rs Then expand src and open the main.rs file.
[Editor] Type:


fn main(){

let a = 30;

let b = 20;

if a>b{

println!(“A is greater than B”);

} else {

println!(“B is greater than A”);

}

}

In the editor, replace the code as shown.
[Editor] Highlight:


If a>b

Here we are checking whether the condition a is greater than b or not.
[Editor] Highlight:


println!(“A is greater than B”);

When the condition is satisfied, the print statement inside the if block gets printed.
[Editor] Highlight:


else {

println!(“B is greater than A”);

}

If not, the print statement in the else block gets executed.
Ctrl + S Save the file.
Switch to terminal Switch to the terminal.
[Terminal] Type:


cd control_flow[Enter]

Go to the project folder control_flow using the cd command.
[Terminal] Type:


cargo run [Enter]

Now type cargo run.
[Terminal] Highlight:


A is greater than B

The print statement in the if block is executed and printed, as the condition is satisfied.
Switch to Editor Switch back to the editor.
[Editor] Modify:


fn main(){

let marks = 50;

if marks>35{

println!(“You are qualified!”);

}

}

In the editor, modify the code as shown.
[Editor] Highlight:

if(marks>35){

println!(“You are qualified!”);

}

Here, in this example, we are considering only the if condition.


When the condition gets satisfied, the block gets executed.


If not, then nothing is printed.

Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Run the project.
[Terminal] Highlight:


You are qualified!

As the condition (marks greater than 35) is satisfied, the block gets executed.


Here, we emphasise that only an if condition can exist without an else statement.

[Editor] Modify:

fn main(){

let a = 5;

if a%2 == 0{

println!(“Number is divisible by 2”);

} else if a%3 == 0{

println!(“Number is divisible by 3”);

} else {

println!(“Number is not divisible by 2 and 3”);

}

}

In the editor, let’s update the code as shown.


This is the if-elseif-else statement.

[Editor] Highlight:


if a%2 == 0{

println!(“Number is divisible by 2”);

}

Here, we are checking a condition if a % 2 == 0 or not.


When this condition is satisfied, the if block gets executed.


When this condition fails, the else if block is checked.

[Editor] Highlight:


else if a%3 == 0{

println!(“Number is divisible by 3”);

}

else if block checks the condition if a % 3 == 0 or not.


When this condition is satisfied, the else if block gets executed.

[Editor] Highlight:

else {

println!(“Number is not divisible by 2 and 3”);

}

When this condition also fails, the else block is executed.

And prints this message as the above two conditions are not satisfied.

Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Now type cargo run.
[Terminal] Highlight:


Number is not divisible by 2 and 3

Number is not divisible by 2 and 3 is printed because the above two conditions are not satisfied.
Only narration That’s how the if - else if - else statements work in Rust.
Next, let’s learn about loops.
Slide: Control Flow - Loops
  • Loops are control structures that are repeatedly executed until a particular condition fails.
  • That means, loops repeat a block of code n number of times until a particular condition fails.
Slide: Control Flow - Loops
  • There are two types of loops supported in Rust
    • For loop and
    • While loop
  • Note: There is no do while loop in Rust
Only Narration Let us take an example and understand Loops better.
[Editor] Type:


fn main(){

loop {

println!(“Hello World!”);

}

}

Go back to the editor and replace the code as shown.
[Editor] Highlight:


loop

loop is a keyword in Rust which iterates a block until it fails.
Ctrl + S Save the file.
Switch to terminal Switch to the terminal.
[Terminal] Type:


cargo run [Enter]

Now type cargo run.
[Terminal] Show:


Hello world

(being printed infinite times)

We can see Hello World being printed infinite times, until the memory in the stack ends.


This is an infinite loop.

Only Narration Press Ctrl + C keys to terminate this loop.
Switch to Editor Switch back to the editor.
[Editor] Modify:


loop {

println!(“Hello, World!”);

break;

}

In the editor, modify the code as shown.
[Editor] Highlight:

break;

Here, we are using break statements to break the execution of the loop.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Run the project.
[Terminal] Highlight:


Hello, World!

Notice now, we can see Hello, World printed only once.


This is because the loop breaks after one execution.


We can even have a condition check and break whenever the condition fails.

Only Narration This is the basic way to loop in Rust.


Next, let us learn about while loop.

Switch to Editor Switch back to the editor.
[Editor] Type:


fn main(){

let mut a = 3;

while a!=0 {

println!(“{}”,a);

a = a - 1;

}

}

In the editor, replace the code as shown.
[Editor] Highlight:

let mut a = 3;

Here we have initialized a mutable variable a and assigned the value 3 to it.
[Editor] Highlight:


while a!=0 {

After this, the while keyword is used to initialize a while loop.


While keyword is followed by the condition a not equal to zero.


Until and unless the condition returns false, the block gets executed.

[Editor] Highlight:


println!(“{}”,a);

a = a - 1;

Here we are printing the number and then reducing the value by 1.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Run the project and see the output.
[Terminal] Highlight:


3

2

1

So now, we have successfully executed the while loop.


Only when the value of a is zero the condition returns false and the block will stop getting executed.


So 0 is not printed.

Only Narration Now let us learn about for loop.
Switch to Editor Switch back to the editor.
[Editor] Type:


fn main(){

let arr = [2,3,5,7,11];

for value in arr.iter() {

println!(“Value = {}”,value);

}

}

In the editor, replace the code as shown.
[Editor] Highlight:


let arr = [2,3,5,7,11];

Here we have initialized an array with few number elements in it.
[Editor] Highlight:

for value in arr.iter() {

So here value means each and every number element present in the array.


In the first iteration, the value will be 2.


And in the second iteration, the value will be 3 and so on.

[Video Editing]:

Notify:

https://doc.rust-lang.org/std/iter/index.html

Rust std module provides three forms of iteration.


Here, we are using iter() method which iterates over the address of T.


For more details, on iter method refer to the link.


In our example, The iter() method will iterate over all the values in the array.

[Editor] Highlight:


println!(“Value = {}”,value);

And, in the block we are printing the value for each and every iteration.
Ctrl + S Save the file.
Switch to terminal Switch back to the terminal.
[Terminal] Type:


cargo run [Enter]

Run the project.
[Terminal] Highlight:


Value = 2

Value = 3

Value = 5

Value = 7

Value = 11

The loop has executed successfully and printed all the values in the array.


We can see the for loop has been executed once for each and every element in the array.


And on reaching the end of the array, the for loop stopped executing.

Only narration That’s how a for loop works in Rust.
Only narration With this we have come to the end of this tutorial.


Let’s summarize.

Slide: Summary In this tutorial, we have learnt:
  • if/else control flow statements
  • Different types of loops and
  • Their syntax and usage
Slide: Assignment As an assignment,
  • Go to the project folder rust-assignment
  • In the main.rs file
    • Create a array named n and assign 10 random numbers to it
    • Loop over the array and
    • Count the number of even values and odd values
    • Print the count of odd and even values
  • Compile and execute the project.
  • Observe the output in the Terminal
Slide: About Spoken Tutorial Project
  • The video at the following link summarises the Spoken Tutorial project.
  • Please download and watch it
Slide: Spoken tutorial workshops
  • We conduct workshops using spoken tutorials and give certificates.
  • For more details, please write to us.
Slide: Forum questions Pls post your timed queries in this forum
Slide: Acknowledgement Spoken Tutorial Project is funded by Ministry of Education, Government of India
Slide: Thanks This is Jayesh signing off. Thank you for joining

Contributors and Content Editors

Kr.jayesh, Nancyvarkey, Pravin1389