← العودة إلى الدورة: Rust from scratch

Week 2 review and practice

الفيديو قريبًا

This lesson is for practice. Instead of new concepts, you will combine what you know about tuples, arrays, functions and control flow in three mini programs. Programming is mostly solving small problems one after another, and the best way to fix Rust syntax in your mind is to write it with your own hands. I suggest you do not copy the code: read it, understand it, close the file and try to write it from memory.

Quick summary

  • Tuples: mixed types, access with t.0 or destructuring with let (a, b) = t.
  • Arrays: [T; N], fixed size, indexes from 0, panic if the index goes out.
  • Functions: typed parameters, return value with -> and last expression without a semicolon.
  • Control flow: if is an expression; loop, while and for; ranges .. and ..=; break, continue and labels.

Practice 1: prime numbers

A function is_prime(n: u32) -> bool decides whether a number is prime. The idea: numbers below 2 are not prime; for the others, it is enough to try divisors from 2 up to the square root. We use while with the condition d * d <= n, so we avoid computing roots with floats. Then a for with a range and a mut counter prints the primes below 30. Notice how the function returns early with return in the easy case.

rust
fn is_prime(n: u32) -> bool {
    if n < 2 {
        return false;
    }
    let mut d = 2;
    while d * d <= n {
        if n % d == 0 {
            return false;
        }
        d += 1;
    }
    true
}

fn main() {
    let mut count = 0;
    for n in 1..30 {
        if is_prime(n) {
            print!("{n} ");
            count += 1;
        }
    }
    println!("\n{count} primes");
}

Practice 2: Fibonacci and arrays

Now we fill a fixed-size array with the Fibonacci sequence, where each number is the sum of the two before it. A [u64; 10] array starts as zeros; we assign the first two and fill the rest with a for over the range 2..10. To modify the array it must be mut. At the end we compute the sum with a loop and return the maximum and minimum in a tuple from a separate function, reviewing tuples and destructuring.

rust
fn extremes(values: &[u64; 10]) -> (u64, u64) {
    let mut lo = values[0];
    let mut hi = values[0];
    for &v in values {
        if v < lo { lo = v; }
        if v > hi { hi = v; }
    }
    (lo, hi)
}

fn main() {
    let mut fib = [0u64; 10];
    fib[1] = 1;
    for i in 2..10 {
        fib[i] = fib[i - 1] + fib[i - 2];
    }
    println!("{:?}", fib);

    let mut total = 0;
    for n in fib {
        total += n;
    }
    let (lo, hi) = extremes(&fib);
    println!("sum = {total}, min = {lo}, max = {hi}");
}

Practice 3: multiplication table

One last guided exercise with nested loops: the table from 1 to 5. The outer loop walks the rows and the inner one the columns. With print! (no newline) we write each product aligned using the format width {:>3}, which right-aligns in three characters. When each row ends we use println!() to change line. Learning the println! formats will save you a lot of time when debugging.

rust
fn main() {
    for row in 1..=5 {
        for col in 1..=5 {
            print!("{:>3}", row * col);
        }
        println!();
    }
}
rust
fn collatz_steps(mut n: u64) -> u32 {
    let mut steps = 0;
    while n != 1 {
        n = if n % 2 == 0 { n / 2 } else { 3 * n + 1 };
        steps += 1;
    }
    steps
}

fn main() {
    for n in 1..=10 {
        println!("{n}: {} steps", collatz_steps(n));
    }
}

اختبر ما تعلمته

السؤال 1 من 5

What does a function whose body ends in "x + 1;" (with a semicolon) return?

✎ ملاحظاتي

محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف

← السابقالتالي →