Start learning free

LESSON 156 OF 409 · LOOPING OVER ARRAY INDICES

Top K Brands V3 - Max in Array in C++

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:

vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
vector<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 cout << ... << endl.

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

C++ needs to_string(...) to join a number to a string with +.

vector<string> brands = {"TechPro", "MegaCorp", "Quantum", "NeoByte", "Zenith"};
vector<int> ratings = {4, 5, 3, 5, 4};

int bestIndex = 0;
for (int i = 1; i < (int)ratings.size(); i++) {
    if (ratings[i] > ratings[bestIndex]) {
        bestIndex = i;
    }
}
cout << "1. " << brands[bestIndex] << " (" << ratings[bestIndex] << ")" << endl;

STEP 1 OF 5
    Ctrl + Enter to check

    Top K Brands V3 in C++

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