Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Control Flow | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 7 of 50

·rust

Control Flow

15 minutes

Course progress14%

Control Flow

Control flow statements direct the execution path of your program based on conditions.

If Expressions

Rust's if is an expression, not just a statement:

let number = 6;
if number % 2 == 0 {
    println!(\
"Even\"); } else if number % 3 == 0 { println!(\"Divisible by 3\"); } else { println!(\"Odd\"); }

If expressions return values:

let condition = true;
let value = if condition { 5 } else { 6 };
println!(\"Value: {}\", value);  // 5

Arms must return the same type.

Loops

Infinite Loop

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

While Loop

let mut count = 0;
while count < 5 {
    println!(\"Count: {}\", count);
    count += 1;
}

For Loop

Iterates over ranges and collections:

// Range loop
for i in 0..5 {
    println!(\"i = {}\", i);  // 0 to 4
}

// Inclusive range
for i in 0..=5 {
    println!(\"i = {}\", i);  // 0 to 5
}

// Over collections
let numbers = [1, 2, 3];
for num in numbers {
    println!(\"Number: {}\", num);
}

Loop Labels

Break or continue outer loops:

'outer: loop {
    for i in 0..10 {
        if i == 5 {
            break 'outer;  // Break outer loop
        }
    }
}

Break with Values

Loops can return values:

let mut count = 0;
let result = loop {
    count += 1;
    if count == 10 {
        break count * 2;  // Return 20
    }
};
println!(\"Result: {}\", result);

Practical Example

fn main() {
    // Find first even number
    let numbers = [1, 3, 5, 6, 7, 8];
    for num in numbers {
        if num % 2 == 0 {
            println!(\"First even: {}\", num);
            break;
        }
    }
    
    // Validate input
    let mut attempts = 0;
    while attempts < 3 {
        println!(\"Try again\");
        attempts += 1;
    }
    
    // Grade calculator
    let score = 85;
    let grade = if score >= 90 {
        'A'
    } else if score >= 80 {
        'B'
    } else if score >= 70 {
        'C'
    } else {
        'F'
    };
    println!(\"Grade: {}\", grade);
}
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonBasic Data TypesContinue to lesson 8FunctionsBack to Rust Fundamentals curriculum