Difference between revisions of "Rust-Programming-Language/C2/Functions-and-Control-Flow/English"
(Created page with "{| border="1" |- || '''Visual Cue''' || '''Narration''' |- || '''Slide 1''' || <span style="color:#000000;">Welcome to the Spoken Tutorial on </span><span style="color:#000000...") |
(No difference)
|
Revision as of 14:31, 6 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
|
| Slide 3
System Requirements
|
This tutorial is recorded using
|
| Slide 4
Prerequisites
|
|
| Slide 5
Code Files
|
|
| First we will see about conditional statements in Rust. | |
| Slide 6
Conditional Statements
|
Rust supports
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
|
|
| 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
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 codefile 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 < 6 becomes false and the loop is terminated.
Save the program.
|
| In the terminal, type cargo run
Check the output.
| |
| Next we will see about For loop. | |
| Slide 7
For loop
|
|
| 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.
i.e it starts at 0 and exclusive on the right. i.e 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
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
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 |
| 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
|
|
| 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 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}"); }
|
In this example, we define a function to calculate the area of a 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 is because it is being considered as a statement and not as a return value. You can use either conventions
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 learn about
|
| Slide 12
|
As an Assignment, do the following:
|
| 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.
|