Start learning free

LESSON 186 OF 289 · LOOPING OVER ARRAY INDICES

Top K Brands V3 in C#: Max in an Array with a for Loop

Practice Read the full explanation

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

You start with:

        string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
        int[] ratings = {4, 5, 3, 5, 4};

Build:

1. MegaCorp (5)

Rules:

  • Keep the position of the best brand so far in bestIndex, starting at 0, and scan the positions from 1 to the end with a loop.
  • Update bestIndex 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 Console.WriteLine(...).

Walk the positions with for (int i = 1; i < ratings.Length; i++) { and compare each rating with the best one so far.

C#'s + on a string and an int converts the integer to text for you.

        string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
        int[] ratings = {4, 5, 3, 5, 4};

        int bestIndex = 0;
        for (int i = 1; i < ratings.Length; i++) {
            if (ratings[i] > ratings[bestIndex]) {
                bestIndex = i;
            }
        }
        Console.WriteLine("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");

STEP 1 OF 5
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Top K Brands V3 in C#, explained

    Problem overview

    Many brands sell the same product. They are stored in two parallel arrays: brands, a string[], and ratings, an int[], where ratings[i] is the rating of brands[i]. The program finds the highest-rated brand by scanning the arrays with a loop and prints it as 1. Brand (rating). If several brands share the top rating, the one listed first wins.

    The starter arrays have five brands: TechPro 4, MegaCorp 5, Quantum 3, NeoByte 5 and Zenith 4. MegaCorp and NeoByte tie for the top rating, and MegaCorp is listed first, so the output is:

    1. MegaCorp (5)

    The previous version compared exactly two brands with if/else. A loop handles any number of brands with the same few lines.

    Approach: keep the position of the best so far

    Scan the list from left to right, remembering the position of the best brand seen so far in bestIndex. At the start, the only brand seen is the first one, so bestIndex is 0. For each later position i, if ratings[i] is strictly higher than ratings[bestIndex], then bestIndex becomes i.

    Storing the position rather than the rating is the key choice. A position works in both arrays: brands[bestIndex] gives the name and ratings[bestIndex] gives the rating. If you stored only the best rating, you would know the score but not whose it is.

    The comparison is strictly greater, so a later brand with an equal rating never replaces the earlier one. That is the tie rule. Tracing the example: bestIndex starts at 0 (rating 4). Position 1 has 5 > 4, so bestIndex becomes 1. Position 2 has 3, no change. Position 3 has 5, which is not strictly greater than 5, so NeoByte does not replace MegaCorp. Position 4 has 4, no change. The final bestIndex is 1.

    Step by step

    1. Create bestIndex as an int set to 0. For now the first brand is the best one we know.
    2. Write a for loop where i starts at 1 and runs while i < ratings.Length. Position 0 is already the current best, so there is nothing to compare it with. The same i is a valid position in both arrays.
    3. Inside the loop, write an if comparing ratings[i] with ratings[bestIndex], strictly greater.
    4. Inside the if, assign bestIndex = i. This brand is the new best, so remember its position.
    5. After the loop, print the winner: "1. ", then brands[bestIndex], then " (", then ratings[bestIndex] and ")", joined with +.

    The solution in C#

            string[] brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
            int[] ratings = {4, 5, 3, 5, 4};
    
            int bestIndex = 0;
            for (int i = 1; i < ratings.Length; i++) {
                if (ratings[i] > ratings[bestIndex]) {
                    bestIndex = i;
                }
            }
            Console.WriteLine("1. " + brands[bestIndex] + " (" + ratings[bestIndex] + ")");
    

    Details worth knowing:

    • Length is a property. Arrays in C# use ratings.Length, without parentheses. Valid indexes are 0 to Length - 1.
    • Array initializers. int[] ratings = {4, 5, 3, 5, 4}; creates an array of exactly five elements. An array cannot grow afterwards. A List<int> can, but arrays are what this lesson uses.
    • Out-of-range access throws. Reading ratings[5] from a five-element array throws an IndexOutOfRangeException. A loop condition of i <= ratings.Length would cause this on its last turn.
    • Parallel arrays. The language does not link brands and ratings. They stay in step only because they have the same length and order.
    • The + with numbers. The printed expression starts with a string, so each rating is joined as text.

    Complexity

    Time: O(n) for n brands. The loop runs n - 1 times and does a constant amount of work per turn. Space: O(1). Only bestIndex and the loop variable are stored, whatever the length of the arrays.

    Edge cases and common mistakes

    • Ties. With the starter data the result is MegaCorp, not NeoByte. Writing >= in the loop would make NeoByte replace MegaCorp and print 1. NeoByte (5). With all five ratings equal to 3, the strict comparison keeps TechPro, the first brand.
    • The best brand is first or last. With ratings 5, 2, 3, 4, 5 the output is 1. TechPro (5). With ratings 1, 2, 3, 4, 5 it is 1. Zenith (5).
    • Only one brand. The loop does not run and the first brand is printed: 1. Solo (2) for a single brand called Solo with rating 2.
    • Storing the rating instead of the index. You can then print the rating but not the brand.
    • Starting at 0. This works, since an element is never strictly greater than itself, but it wastes one comparison.
    • An empty array. ratings[0] would throw. The lesson's data is never empty.

    Testing

    • The starter data gives 1. MegaCorp (5).
    • Ratings 1, 2, 3, 4, 5 give 1. Zenith (5).
    • Ratings 5, 2, 3, 4, 5 give 1. TechPro (5).
    • Ratings 3, 3, 3, 3, 3 give 1. TechPro (3).
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free