<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Rasheed Olaleye</title>
    <description>The latest articles on Forem by Rasheed Olaleye (@rasheedolaleye).</description>
    <link>https://forem.com/rasheedolaleye</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1106491%2Fe866eb19-d278-4e7d-b9fc-2927f79db084.jpeg</url>
      <title>Forem: Rasheed Olaleye</title>
      <link>https://forem.com/rasheedolaleye</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/rasheedolaleye"/>
    <language>en</language>
    <item>
      <title>HOW TO USE CONTROL FLOW IN THE RUST PROGRAMMING LANGUAGE</title>
      <dc:creator>Rasheed Olaleye</dc:creator>
      <pubDate>Thu, 06 Jul 2023 05:14:13 +0000</pubDate>
      <link>https://forem.com/rasheedolaleye/how-to-use-control-flow-in-the-rust-programming-language-57m3</link>
      <guid>https://forem.com/rasheedolaleye/how-to-use-control-flow-in-the-rust-programming-language-57m3</guid>
      <description>&lt;p&gt;Easy steps to implement control flow for beginners&lt;/p&gt;

&lt;p&gt;Just as decisions are crucial for individuals, in programming, a program also makes decisions based on specific conditions.&lt;/p&gt;

&lt;p&gt;Prerequisite: Foundational programming knowledge&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Table of contents&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;What is Control Flow?&lt;/li&gt;
&lt;li&gt;Real-Life Examples of Control Flow&lt;/li&gt;
&lt;li&gt;Using IF Expressions&lt;/li&gt;
&lt;li&gt;Using Loop Expressions&lt;/li&gt;
&lt;li&gt;Using While Expressions&lt;/li&gt;
&lt;li&gt;Using For Expressions&lt;/li&gt;
&lt;li&gt;Peculiarities of Rust&lt;/li&gt;
&lt;li&gt;Conclusion&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  What is Control Flow?
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
Control flow refers to the sequence in which instructions or statements are executed in a program. It allows the program to make decisions and perform different actions based on specific conditions. By using control flow structures, such as conditional statements (e.g., if-else statements) and loops, programmers can create programs that can adapt and respond to different situations.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;
&lt;h2&gt;
  
  
  Real-Life Examples Of Control Flow
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
1.&lt;strong&gt;Alarm Clock&lt;/strong&gt;: When you set an alarm for a specific time, it operates autonomously based on the condition. For instance, if you want to wake up at 4 am, the alarm will ring when the designated time is reached.&lt;br&gt;
2.&lt;strong&gt;Traffic Light&lt;/strong&gt;: Control flow is used in the context of traffic lights to decide which color light should be displayed at a specific time. Based on set standards and conditions, the control flow mechanism enables the sequential switching between the green, red, and yellow lights. This guarantees the orderly and secure passage of cars and people crossing the street at crossings.&lt;br&gt;
3.&lt;strong&gt;ATMs(Automated Teller Machine)&lt;/strong&gt;: When you insert your ATM card into a machine, it performs a series of checks to verify your identity. One of these checks involves asking you to enter your PIN (Personal Identification Number). If the entered PIN matches the one associated with your card, the ATM grants you access to perform various actions, such as withdrawing cash, transferring funds, or conducting other banking transaction.&lt;/p&gt;

&lt;p&gt;**&lt;/p&gt;
&lt;h2&gt;
  
  
  Using IF expression
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
An &lt;code&gt;if&lt;/code&gt; expression can be used to branch your code depending on conditions. The structure is simple: if a condition is met, execute a block of code; if not, do not execute it. For example, throughout this article, we will be solving a problem of calculating the number of days using a control flow&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let day = "Tuesday";
    let num_days = if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
        day == "Thursday" || day == "Friday" {
            5
        } else if day == "Saturday" || day == "Sunday" {
            2
        } else {
            println!("Invalid day!");
            -1
        };

    println!("There are {} days in the week.", num_days)
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Before the &lt;code&gt;IF&lt;/code&gt; statement, I declare a variable using the &lt;code&gt;LET&lt;/code&gt;keyword and initialize it to Tuesday, then I declare another variable num_days to hold the result of the conditions. I use a semicolon to end the statement which assigns value to a statement.&lt;/p&gt;

&lt;p&gt;Try running this code, you would see, this&lt;br&gt;
Note: cargo is a keyword in Rust used to execute a line of code just like npm in javascript&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PS C:\Users\ELITEBOOK 840 G3\Rust\Practice&amp;gt; cargo run
warning: crate `Practice` should have a snake case name      
  |
  = help: convert the identifier to snake case: `practice`   
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning     
    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target\debug\Practice.exe`
There are 5 days in the week.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Using Loop expression&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Using a loop can sometimes be tricky or may seem somewhat unusual. However, when you need to iterate over an object in Rust, a loop may be a better choice. Let's explore this further.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let day = "Tuesday";
    let mut num_days = -1;


    loop {
        if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
            day == "Thursday" || day == "Friday" {
                num_days = 5;
                break;
        } else if day == "Saturday" || day == "Sunday" {
                num_days = 2;
                break;
           } else {
                println!("Invalid day!");
                break;
            }
    }


    println!("There are {} days in the week.", num_days);
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first code we wrote earlier used an &lt;code&gt;IF&lt;/code&gt; statement. Once a condition is satisfied, the corresponding block of code is executed, and the control flow moves to the next block of code. In contrast, a &lt;code&gt;LOOP&lt;/code&gt; continues indefinitely until a condition is met. This code is more concise than the &lt;code&gt;IF&lt;/code&gt; statement.&lt;/p&gt;

&lt;p&gt;Let's run the code again and see the output&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cargo run
warning: crate `Practice` should have a snake case name      
  |
  = help: convert the identifier to snake case: `practice`   
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning     
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target\debug\Practice.exe`
There are 5 days in the week
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Using While expression&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;While is executed when corresponding code is true.&lt;br&gt;
let's check&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  fn main() {
    let day = "Tuesday";
    let mut num_days = -1;


    while num_days == -1 {
        if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
            day == "Thursday" || day == "Friday" {
                num_days = 5;
        } else if day == "Saturday" || day == "Sunday" {
                num_days = 2;
        } else {
            println!("Invalid day!");
            break;
        }
    }


    println!("There are {} days in the week.", num_days);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;**&lt;/p&gt;

&lt;h2&gt;
  
  
  Using For Expression
&lt;/h2&gt;

&lt;p&gt;**&lt;br&gt;
The for expression in Rust is used to iterate over collections or ranges with known lengths.&lt;br&gt;
It provides a convenient and concise way to loop over elements without explicitly managing indices .It is commonly used with arrays, vectors, strings, and other iterable types in Rust.&lt;br&gt;
Examples of how to use For &lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Examples of how to use For *&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let day = "Tuesday";
    let mut num_days = -1;


    for x in 0..1 {
        if day == "Monday" || day == "Tuesday" || day == "Wednesday" ||
            day == "Thursday" || day == "Friday" {
                num_days = 5;
        } else if day == "Saturday" || day == "Sunday" {
                num_days = 2;
        } else {
            println!("Invalid day!");
            break;
        }
    }


    println!("There are {} days in the week.", num_days);
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can see that the code above is not different from the others we have written. For first check for the range between 0 to 1 before interaction started. &lt;/p&gt;

&lt;p&gt;_&lt;br&gt;
Let run and see the output_&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cargo run
warning: crate `Practice` should have a snake case name      
  |
  = help: convert the identifier to snake case: `practice`   
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning     
    Finished dev [unoptimized + debuginfo] target(s) in 0.03s
     Running `target\debug\Practice.exe`
There are 5 days in the week
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We can also use it to iterate over array, vector, string.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterating over  Array:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let days = ["Monday", "Tuesday", "Wednesday", "Thursday"];

    for day in &amp;amp;days {
        println!("Day of the week: {}", day);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code defines an array of the days of the week. It uses a for loop to print each day. The &lt;code&gt;&amp;amp;&lt;/code&gt; means we're borrowing the array's values.&lt;/p&gt;

&lt;p&gt;Let us run this code&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cargo run
warning: crate `Practice` should have a snake case name
  |
  = help: convert the identifier to snake case: `practice`
  = note: `#[warn(non_snake_case)]` on by default

    Finished dev [unoptimized + debuginfo] target(s) in 0.04s
     Running `target\debug\Practice.exe`
Day of the week: Monday
Day of the week: Tuesday
Day of the week: Wednesday
Day of the week: Thursday
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Iterating over a vector:&lt;/strong&gt;&lt;br&gt;
A vector is a dynamic array that can store and change a variable number of elements of the same type. It’s represented by Vec, where T is the type of elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main() {
    let days = vec!["Monday", "Tuesday", "Wednesday", "Thursday"];

    for day in &amp;amp;days {
        println!("Day of the week: {}", day);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code  created a vector of days using the vec! macro. The for loop then prints each day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Iterating over a string:&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;String is combination of characters stored in memory. It is usually put in a quotation mark.String flour in Rust is called String.&lt;br&gt;
for example&lt;br&gt;
&lt;code&gt;let a: String = String::from("Hello, World");&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
fn main() {
    let message = "Hello, Rust progamming language!";

for c in message.chars() {
    println!("Character: {}", c);
}

}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Peculiarities of Rust Control flow&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Here we are going to discuss the challenges in rust while using control flow. Every programming language has its peculiar challenges. &lt;/p&gt;

&lt;p&gt;Let's use the examples below to learn one of the peculiarities of Rust&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
fn main() {
 let days = 10; 
if days { 
println!("days was three"); } }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we are going to discuss the challenges in Rust when using control flow. Every programming language has its own peculiar challenges.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   Compiling Practice v0.1.0 (C:\Users\ELITEBOOK 840 G3\Rust\Practice)
error[E0308]: mismatched types
 --&amp;gt; src\main.rs:3:7
  |
3 |    if days { 
  |       ^^^^ expected `bool`, found integer

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the error messages displayed by the compiler, it expects a boolean value. This means that you must always include a boolean expression in your code when dealing with an integer.&lt;br&gt;
 Let's take a look at the correct code to better understand this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn main () {
Let days = 10;
If days &amp;gt; 5{
println("days was three")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cargo run
   Compiling Practice v0.1.0 (C:\Users\ELITEBOOK 840 G3\Rust\practice)
warning: crate `Practice` should have a snake case name
  |
  = help: convert the identifier to snake case: `practice`
  = note: `#[warn(non_snake_case)]` on by default

warning: `Practice` (bin "Practice") generated 1 warning
    Finished dev [unoptimized + debuginfo] target(s) in 0.79s
     Running `target\debug\Practice.exe`
days was three
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The result does not display error because we have use a bool.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Conclusion&lt;/strong&gt;&lt;br&gt;
From the above code examples, we have seen how Rust handles control flow. The idiomatic way of writing control flow, as explained earlier, makes the code simple and easy to read. The choice of which construct to use depends on the specific requirements and readability goals of the code. Thank you for reading.&lt;/p&gt;

</description>
      <category>rust</category>
      <category>programming</category>
      <category>beginners</category>
      <category>howto</category>
    </item>
  </channel>
</rss>
