Start learning free

LESSON 164 OF 414 · LOOPING OVER ARRAY INDICES

Top K Brands V3 - Max in Array in Rust

Practice

Many brands sell the same product, stored in two parallel vectors: ratings[i] is the rating of brands[i]. Find the highest-rated brand by scanning with a loop.

You start with: an empty editor (no starter code). Declare this data yourself:

let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
let ratings = vec![4, 5, 3, 5, 4];

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in best_index, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update best_index only on a strictly higher rating. If two brands share the top rating, the one listed first wins (MegaCorp at position 1, not NeoByte at position 3).
  • Format the winner as "1. Brand (rating)" and print it with println!(...).

Walk the positions with for i in 1..ratings.len() { and compare each rating with the best one so far.

format!("1. {} ({})", brand, rating) builds text from several values, numbers included.

        let brands = vec!["TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"];
        let ratings = vec![4, 5, 3, 5, 4];
        let mut best_index = 0;
        for i in 1..ratings.len() {
            if ratings[i] > ratings[best_index] {
                best_index = i;
            }
        }
        println!("1. {} ({})", brands[best_index], ratings[best_index]);

STEP 1 OF 7
    Ctrl + Enter to check

    Top K Brands V3 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free