Difference between revisions of "Rust-Programming-Language/C2/Functions-and-Control-Flow/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
 
Line 100: Line 100:
 
The condition must be true to run the code wrapped to it.
 
The condition must be true to run the code wrapped to it.
  
Press '''ctrl and s '''to save the file.
+
Press '''Ctrl''' and '''S ''' to save the file.
  
 
Now let us run the program.
 
Now let us run the program.
 
|-
 
|-
|| In the menu bar, click on '''Terminal''' and select '''New Terminal.'''
+
|| In the menu bar, click on '''Terminal''' and select '''New Terminal'''.
  
 
|| In the menu bar, click on '''Terminal''' and select '''New Terminal.'''
 
|| In the menu bar, click on '''Terminal''' and select '''New Terminal.'''
Line 143: Line 143:
 
}
 
}
 
|| This example has a mutable variable named '''count''' which is assigned to the value 0.
 
|| This example has a mutable variable named '''count''' which is assigned to the value 0.
 +
 
A loop is created in which it increases the '''count''' variable by 1.
 
A loop is created in which it increases the '''count''' variable by 1.
  
 
It prints the value of count in the current iteration.  
 
It prints the value of count in the current iteration.  
  
It will also check for the '''if '''statement condition.  
+
It will also check for the '''if ''' statement condition.  
  
 
When the variable count will be equal to 5, it will stop executing and come out of the loop.  
 
When the variable count will be equal to 5, it will stop executing and come out of the loop.  
  
If there is no if statement, it will execute infinitely.Press '''ctrl and s '''to save the file.
+
If there is no if statement, it will execute infinitely.
 +
 
 +
Press '''Ctrl''' and '''S ''' to save the file.
  
 
Let us run the program
 
Let us run the program
  
 
|-
 
|-
||
+
||In the terminal, type '''cargo run'''.
|| In the terminal, type '''cargo run'''
+
|| In the terminal, type '''cargo run'''.
  
 
We can see the count variable is printed from 1 to 5.  
 
We can see the count variable is printed from 1 to 5.  
Line 166: Line 169:
 
|| Next we will see how the '''while''' loop works.
 
|| Next we will see how the '''while''' loop works.
  
Replace the code from the codefile with the '''while''' loop program.
+
Replace the code from the Code file with the '''while''' loop program.
 
|-
 
|-
 
|| fn main() {
 
|| fn main() {
Line 185: Line 188:
 
After the 5th iteration, the value of the counter will be 6.
 
After the 5th iteration, the value of the counter will be 6.
  
So the condition, counter < 6 becomes false and the loop is terminated.
+
So the condition, counter is less than 6 becomes false and the loop is terminated.
  
 
Save the program.
 
Save the program.
 
|-
 
|-
||
+
||In the terminal, type '''cargo run'''.
|| In the terminal, type '''cargo run'''
+
|| In the terminal, type '''cargo run'''.
  
 
Check the output.
 
Check the output.
Line 203: Line 206:
 
||
 
||
 
* The '''for''' loop iterates over a range or a collection
 
* The '''for''' loop iterates over a range or a collection
* An '''iterator '''which provides a way to access elements one at a time.
+
* An '''iterator ''' which provides a way to access elements one at a time.
 
* In a '''For''' loop, many collections like arrays, vectors, and ranges, implement the '''Iterator'''  
 
* In a '''For''' loop, many collections like arrays, vectors, and ranges, implement the '''Iterator'''  
  
Line 221: Line 224:
 
A range with two dots like 0..11 is inclusive on the left.
 
A range with two dots like 0..11 is inclusive on the left.
  
i.e it starts at 0 and exclusive on the right. i.e ends at 10
+
That is, it starts at 0 and exclusive on the right
 +
that is, ends at 10.
  
This program will print numbers from 0 to 10
+
This program will print numbers from 0 to 10.
 
|-
 
|-
 
||  
 
||  
Line 242: Line 246:
 
||  In this code, we have an array '''‘data’''' containing five integers.  
 
||  In this code, we have an array '''‘data’''' containing five integers.  
  
The '''data.iter() '''method creates an iterator for the array '''data'''.
+
The '''data.iter() ''' method creates an iterator for the array '''data'''.
  
 
The '''for''' loop takes each element produced by the iterator and binds it to the variable '''data'''.  
 
The '''for''' loop takes each element produced by the iterator and binds it to the variable '''data'''.  
Line 252: Line 256:
 
Let us execute the program.
 
Let us execute the program.
 
|-
 
|-
||
+
|| In the terminal, type '''cargo run'''.
|| In the terminal, type '''cargo run'''
+
 
 +
|| In the terminal, type '''cargo run'''.
  
 
We can see the array elements are printed in sequence.
 
We can see the array elements are printed in sequence.
Line 264: Line 269:
 
|| '''fn''' main() {
 
|| '''fn''' main() {
  
<div style="color:#252525;">for i in (1..=11).rev() {
+
for i in (1..=11).rev() {
<div style="color:#252525;">println!("{i}...");
+
println!("{i}...");
<div style="color:#252525;">}
+
}
<div style="color:#252525;">println!("Launch!");
+
println!("Launch!");
 
}
 
}
 
|| Copy and paste the code from the code file.
 
|| Copy and paste the code from the code file.
  
If we want the range to include 11 as well, we can write it as '''(1..=11).'''  
+
If we want the range to include 11 as well, we can write it as '''(1..=11)'''.
 +
 
 
This is known as an inclusive range.
 
This is known as an inclusive range.
  
The '''rev() '''method is applied to the range to produce a reverse iterator.  
+
The '''rev() ''' method is applied to the range to produce a reverse iterator.  
  
 
This means the numbers will be fetched in reverse order.
 
This means the numbers will be fetched in reverse order.
  
<div style="color:#252525;">save the file.
+
Save the file.
  
<div style="color:#252525;">Let us check the output
+
Let us check the output.
 
|-
 
|-
||
+
|| In the terminal, type '''cargo run'''.
|| In the terminal, type '''cargo run'''
+
|| In the terminal, type '''cargo run'''.
  
 
We can see the output displayed in the reverse order as expected.
 
We can see the output displayed in the reverse order as expected.
Line 299: Line 305:
 
println!("Launch!");
 
println!("Launch!");
 
}
 
}
|| <div style="color:#252525;">Copy and paste the code from the code file
+
|| Copy and paste the code from the code file
  
The''' if '''statement checks if''' i '''is divisible by 2.
+
The''' if '''statement checks if ''' i ''' is divisible by 2.
  
 
If this condition is true, the '''continue''' statement is executed.  
 
If this condition is true, the '''continue''' statement is executed.  
Line 307: Line 313:
 
The '''continue''' statement skips the rest of the loop body for the current iteration and moves to the next one.
 
The '''continue''' statement skips the rest of the loop body for the current iteration and moves to the next one.
  
Save the program
+
Save the program.
 
|-
 
|-
||
+
||Point to the output.
 
|| In the terminal, check the output.
 
|| In the terminal, check the output.
  
Line 321: Line 327:
 
'''Functions'''
 
'''Functions'''
 
||
 
||
* It is a set of statements to perform a specific task
+
* It is a set of statements to perform a specific task.
 
* Functions organize the program into logical blocks of code.
 
* Functions organize the program into logical blocks of code.
 
* Functions make the code reusable.
 
* Functions make the code reusable.
Line 343: Line 349:
 
Notice that we are calling the function from inside '''main()'''.
 
Notice that we are calling the function from inside '''main()'''.
  
In Rust, '''main() '''is also a function known as a built-in function that has a special meaning.  
+
In Rust, '''main() ''' is also a function known as a built-in function that has a special meaning.  
 
|-
 
|-
 
||
 
||
Line 365: Line 371:
  
 
Here, a and b are function parameters.
 
Here, a and b are function parameters.
 +
 
i32 is the data type of parameters.
 
i32 is the data type of parameters.
 +
 
12 and 10 are known as function arguments that are passed to the '''add''' function.
 
12 and 10 are known as function arguments that are passed to the '''add''' function.
  
Line 399: Line 407:
 
Change the program to return length*breadth
 
Change the program to return length*breadth
  
||  In this example, we define a function to calculate the area of a rectangle.  
+
||  In this example, we define a function to calculate the area of rectangle.  
  
 
The area function takes two parameters, length and breadth, both of type i32.  
 
The area function takes two parameters, length and breadth, both of type i32.  
Line 409: Line 417:
 
In the next line, notice the lack of a semicolon after length * breadth.
 
In the next line, notice the lack of a semicolon after length * breadth.
  
In Rust, the absence of a semicolon signifies that this line is an expression.
+
In '''Rust''', the absence of a semicolon signifies that this line is an expression.
  
 
The result value is returned by the function.  
 
The result value is returned by the function.  
 +
 
Save the file and run the program.  
 
Save the file and run the program.  
  
 
We can see the output as the area of the rectangle is 30.
 
We can see the output as the area of the rectangle is 30.
  
Now let us add a semicolon at the end of length into Breadth statement .
+
Now let us add a semicolon at the end of length into Breadth statement.
  
 
Let us run the program and see how the program works.
 
Let us run the program and see how the program works.
Line 431: Line 440:
 
* return length*breadth with semicolon
 
* return length*breadth with semicolon
 
for returning the value.
 
for returning the value.
Save the file and run the program
+
 
 +
Save the file and run the program.
  
 
We can observe that the area of the rectangle is 30.
 
We can observe that the area of the rectangle is 30.
Line 443: Line 453:
  
 
'''Summary'''
 
'''Summary'''
|| In this tutorial, we learn about
+
|| In this tutorial, we learnt about
  
 
* Control Flow Statement and
 
* Control Flow Statement and
Line 489: Line 499:
  
 
'''Acknowledgement'''
 
'''Acknowledgement'''
|| We would like to thank '''Vishal Pokuri from VIT Vellore '''for content contribution.
+
|| We would like to thank '''Vishal Pokuri from VIT Vellore ''' for content contribution.
 
|-
 
|-
 
|| '''Slide 18'''
 
|| '''Slide 18'''

Latest revision as of 11:58, 27 May 2025

Visual Cue Narration
Slide 1 Welcome to the Spoken Tutorial on Functions and Control Flow in Rust.
Slide 2

Learning Objectives

In this tutorial, we will learn about
  • Control Flow Statement and
  • Functions
Slide 3

System Requirements

This tutorial is recorded using
  • Ubuntu Linux OS version 22.04
  • Rust 1.80.0
  • Visual Studio Code 1.19.0
Slide 4

Prerequisites

  • You should be familiar with compiling and running Rust files
  • If not go through the prerequisite Rust tutorial on this website
Slide 5

Code Files

  • The files used in this tutorial are provided in the Code files link of this tutorial page
  • Please download and extract the files.
  • Make a copy and then use them while practicing.
First we will see about conditional statements in Rust.
Slide 6

Conditional Statements

Rust supports
  • if
  • else if
  • else

statements for making decisions based on conditions.

It always returns a boolean value.

Open Visual code editor Let us open the visual code editor and understand the control statements with examples.
In the menu bar, click on terminal and select New Terminal

We can see a terminal window at the bottom.

> cd MyRustProject

> cargo new functions

Go to our working directory MyRustProject as explained earlier.

Type the command cargo new functions and press Enter

Open the created project as shown.

In the main.rs file, copy and paste the code from the code file.
fn main() {

let n = 100; if n>100{ println!("Greater than 100"); }else if n==100{ println!("Equal to 100"); }else { println!("Smaller than 100"); }

}

Let us look at this example for an if else statement.

If n is greater than 100, it prints a “greater than 100” statement.

If n equals 100, the second print statement will be executed.

If n is less than 100, it prints “smaller than 100”.

You can include multiple else if statements to check multiple conditions in sequence.

The condition must be true to run the code wrapped to it.

Press Ctrl and S to save the file.

Now let us run the program.

In the menu bar, click on Terminal and select New Terminal. In the menu bar, click on Terminal and select New Terminal.
> cargo run In the terminal, type cargo run to see the output.

The output shows “equal to 100” as we have assigned n as 100 in the program.

Next let us see loop statements in Rust
Slide

Loop

  • A loop is used to repeat a block of code until the specified condition is met
  • The loop keyword creates an infinite loop unless you explicitly break out of it
  • Rust provides several ways to loop, including loop, while, and for
Let us see an example for a loop program.

Clear the code window and replace the code from the code file as shown.

fn main() {

let mut count = 0; loop { count += 1; println!("Count: {}", count); if count == 5 { break; } } }

This example has a mutable variable named count which is assigned to the value 0.

A loop is created in which it increases the count variable by 1.

It prints the value of count in the current iteration.

It will also check for the if statement condition.

When the variable count will be equal to 5, it will stop executing and come out of the loop.

If there is no if statement, it will execute infinitely.

Press Ctrl and S to save the file.

Let us run the program

In the terminal, type cargo run. In the terminal, type cargo run.

We can see the count variable is printed from 1 to 5.

It stops executing when the count reaches 5.

Next we will see how the while loop works.

Replace the code from the Code file with the while loop program.

fn main() {

let mut counter = 1; // usage of while loop while counter < 6 { println!("{}", counter); counter += 1; } }

The while loop runs as long as a condition is true.

Here, the loop keeps running till the counter variable is less than 6.

Inside the loop, we are increasing the value of the counter by 1.

After the 5th iteration, the value of the counter will be 6.

So the condition, counter is less than 6 becomes false and the loop is terminated.

Save the program.

In the terminal, type cargo run. In the terminal, type cargo run.

Check the output.

Next we will see about For loop.
Slide 7

For loop

  • The for loop iterates over a range or a collection
  • An iterator which provides a way to access elements one at a time.
  • In a For loop, many collections like arrays, vectors, and ranges, implement the Iterator
Slide 8

For loop -example

fn main() { for n in 0..11 { println!("{}", n); } }

The For loop has a definite start and endpoint with increment for each iteration.

A range with two dots like 0..11 is inclusive on the left.

That is, it starts at 0 and exclusive on the right that is, ends at 10.

This program will print numbers from 0 to 10.

Next let us see an example of a for loop with an iterator method.

Clear the code window and copy and paste the code from the code file.

fn main() {

let data = [2, 1, 17, 99, 34, 56]; // iterator //let numbers_iterator = data.iter(); for i in data.iter(){ println!("{}", i); } }

In this code, we have an array ‘data’ containing five integers.

The data.iter() method creates an iterator for the array data.

The for loop takes each element produced by the iterator and binds it to the variable data.

Inside the for loop, println is used to print the value of each element.

Save the file.

Let us execute the program.

In the terminal, type cargo run. In the terminal, type cargo run.

We can see the array elements are printed in sequence.

We will learn some more concepts that work with a for loop.

Let us see how to use a reverse method in the for loop.

fn main() {

for i in (1..=11).rev() { println!("{i}..."); } println!("Launch!"); }

Copy and paste the code from the code file.

If we want the range to include 11 as well, we can write it as (1..=11).

This is known as an inclusive range.

The rev() method is applied to the range to produce a reverse iterator.

This means the numbers will be fetched in reverse order.

Save the file.

Let us check the output.

In the terminal, type cargo run. In the terminal, type cargo run.

We can see the output displayed in the reverse order as expected.

Next we will see how to print odd numbers using a for loop.
fn main() {

for i in (1..11).rev() { if i % 2 == 0 { continue; } println!("{i}..."); } println!("Launch!"); }

Copy and paste the code from the code file

The if statement checks if i is divisible by 2.

If this condition is true, the continue statement is executed.

The continue statement skips the rest of the loop body for the current iteration and moves to the next one.

Save the program.

Point to the output. In the terminal, check the output.

We can see the odd numbers are printed between 11 and 1.

Next we will see about Functions in Rust.
Slide 9

Functions

  • It is a set of statements to perform a specific task.
  • Functions organize the program into logical blocks of code.
  • Functions make the code reusable.
  • It structures your programs and makes them more readable and maintainable.
Slide 10

Function - Example // define a function fn greet() { println!("Hello, World!"); } fn main() { //function call greet(); }

Here, we have created a greet() function that prints "Hello, World!" .

To invoke the created function, we need to make a function call.

Notice that we are calling the function from inside main().

In Rust, main() is also a function known as a built-in function that has a special meaning.

Next we will see how we can create a function with parameters.
Let us understand the working of functions with examples.

In the main.rs file, replace the code from the code file.

// define an add function that takes in two parameters

fn add(a: i32, b: i32) { let sum = a + b; println!("Sum of a and b = {}", sum); } fn main() { // call add function with arguments add(12, 10); }

In this example, the add function takes 2 parameters and gives the sum as output.

Here, a and b are function parameters.

i32 is the data type of parameters.

12 and 10 are known as function arguments that are passed to the add function.

That means 12 is assigned to a and 10 is assigned to b.

Save the file.

In the terminal, type cargo run . In the terminal, type cargo run and see the output.

It prints the sum of a and b as 22.

Next we will see an example for a function with return value.

Replace the code as shown.

fn area(length: i32, breadth: i32) -> i32 {

   length * breadth

}

fn main() {

    let k = area(5, 6);

    println!("Area of the rectangle = {k}");

}


Change the program to return length*breadth

In this example, we define a function to calculate the area of rectangle.

The area function takes two parameters, length and breadth, both of type i32.

-> i32 - right arrow i32 before the opening curly bracket indicates the function's return type.

It returns an i32 value representing the area of the rectangle.

In the next line, notice the lack of a semicolon after length * breadth.

In Rust, the absence of a semicolon signifies that this line is an expression.

The result value is returned by the function.

Save the file and run the program.

We can see the output as the area of the rectangle is 30.

Now let us add a semicolon at the end of length into Breadth statement.

Let us run the program and see how the program works.

It would not return a value and cause a compilation error.


This time we get an error, remove this semicolon to return this value.

This is because it is being considered as a statement and not as a return value.

You can use either conventions 

  • length*breadth without semicolon or
  • return length*breadth with semicolon

for returning the value.

Save the file and run the program.

We can observe that the area of the rectangle is 30.

This brings us to the end of this tutorial.

Let us summarize.

Slide 11

Summary

In this tutorial, we learnt about
  • Control Flow Statement and
  • Functions
Slide 12


Assignment

As an Assignment, do the following:
  • In the main.rs file
    • Create a function that accepts a number as a parameter
    • Print EVEN if the number is even
    • Else print ODD
  • Compile and execute the project.
  • Observe the output in the Terminal
Slide 13

About Spoken Tutorial Project

This video summarizes the Spoken Tutorial project.

Please download and watch it.

Slide 14

Spoken Tutorial Workshops

The Spoken Tutorial Project Team conducts workshops and gives certificates.

For more details, please write to us.

Slide 15

Forum for specific questions

Please post your timed queries in this forum
Slide 16

Acknowledgement

Spoken Tutorial project was established at IIT Bombay by the Ministry of Education(MoE), Govt of India
Slide 17

Acknowledgement

We would like to thank Vishal Pokuri from VIT Vellore for content contribution.
Slide 18

Thank You

This tutorial is contributed by Nirmala Venkat and Ketki Bhamble from the spoken tutorial team.

Thank you for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat