Start learning free

LESSON 184 OF 289 · LOOPING OVER ARRAY INDICES

Employee of the Year V4 in C#: Finding the Best Index in a Loop

Practice Read the full explanation

A whole team is competing. Use a for loop over the arrays to find the most productive employee, then print their 15% bonus.

You start with:

        string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
        int[] productivities = {83, 133, 97, 150, 120};
        int[] salaries = {135000, 335000, 210000, 250000, 180000};

Build:

Alice Chen
Bonus: $37500

Rules:

  • Index i in all three arrays refers to the same employee.
  • The winner is whichever employee has the highest productivity. If two employees share the highest productivity, the one listed first wins.
  • The winner's bonus is 15% of their salary, rounded down to a whole number.
  • Print the winner's name on the first line, then "Bonus: $<amount>" on the second.

Start with int bestIndex = 0 and loop over the other indices with for (int i = 1; i < names.Length; i++). Inside the loop, update the best index only when productivities[i] > productivities[bestIndex]: a strict comparison keeps the first employee on a tie.

Dividing two whole numbers (int) drops the fraction, so salaries[bestIndex] * 15 / 100 is already rounded down: int bonus = salaries[bestIndex] * 15 / 100;

+ turns the int into text: Console.WriteLine("Bonus: $" + bonus);

        string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
        int[] productivities = {83, 133, 97, 150, 120};
        int[] salaries = {135000, 335000, 210000, 250000, 180000};

        int bestIndex = 0;
        for (int i = 1; i < names.Length; i++) {
            if (productivities[i] > productivities[bestIndex]) {
                bestIndex = i;
            }
        }
        int bonus = salaries[bestIndex] * 15 / 100;
        Console.WriteLine(names[bestIndex]);
        Console.WriteLine("Bonus: $" + bonus);

STEP 1 OF 6
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Employee Of The Year V4 in C#, explained

    Problem overview

    The data now lives in three parallel arrays: names, productivities and salaries. Position i in all three describes the same employee. The program must find the employee with the highest productivity, then print their name and a bonus of 15% of their salary, rounded down. If several employees share the highest productivity, the one listed first wins.

    For the five employees in the starter code, Alice Chen has the top productivity, 150, and a salary of 250000. Her bonus is 250000 * 15 / 100 = 37500:

    Alice Chen
    Bonus: $37500

    The previous version compared a fixed number of employees with an if chain. A chain needs one more branch for every extra employee, while a loop works the same for any number.

    Approach: remember the best position so far

    The idea is to scan the list once while keeping the index of the best employee seen so far. Start by assuming employee 0 is the best. Then look at each of the others in turn. If someone's productivity is strictly higher than the productivity of the current best, they become the new best.

    The program stores the index, not the productivity value. One index can be used in all three arrays: names[bestIndex], productivities[bestIndex] and salaries[bestIndex]. If you stored just the highest score, you would have no way to get back to the name and the salary.

    The comparison must be strictly greater. When a later employee only equals the current best, the earlier one keeps the lead, which is the tie rule. With the example data the best index moves from 0 (83) to 1 (133) and then to 3 (150). Employee 2 (97) and employee 4 (120) do not beat 150.

    Step by step

    1. Create bestIndex and set it to 0. Before any comparison, employee 0 is the best employee we know about.
    2. Write a for loop from 1 to the end. The loop variable i starts at 1 and the condition is i < names.Length. Position 0 is already the current best, so there is nobody to compare it with. Starting at 1 compares everyone else against it.
    3. Inside the loop, compare productivities[i] with productivities[bestIndex]. If the first is strictly greater, assign bestIndex = i.
    4. After the loop, compute bonus as salaries[bestIndex] * 15 / 100. Integer division rounds down.
    5. Print names[bestIndex] on its own line.
    6. Print the bonus as "Bonus: $" + bonus. The dollar sign is just text inside the quotes.

    The solution in C#

            string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
            int[] productivities = {83, 133, 97, 150, 120};
            int[] salaries = {135000, 335000, 210000, 250000, 180000};
    
            int bestIndex = 0;
            for (int i = 1; i < names.Length; i++) {
                if (productivities[i] > productivities[bestIndex]) {
                    bestIndex = i;
                }
            }
            int bonus = salaries[bestIndex] * 15 / 100;
            Console.WriteLine(names[bestIndex]);
            Console.WriteLine("Bonus: $" + bonus);
    

    Details worth knowing:

    • Arrays have a fixed length. names.Length is a property, not a method, so there are no parentheses. It is the number of elements, and valid indexes run from 0 to Length - 1. That is why the loop condition is i < names.Length.
    • The array initializer. string[] names = {"John Doe", ...}; creates the array and sets its size from the number of values. It is shorthand for new string[] { ... } and works in a declaration like this one.
    • Bounds are checked. Reading productivities[5] from a five-element array throws an IndexOutOfRangeException with the message Index was outside the bounds of the array. A loop written as i <= names.Length hits this on its last turn.
    • Parallel arrays. Nothing in the language ties the three arrays together. They stay consistent only if you keep them the same length and in the same order. Using one index for all three is the discipline that makes it work.

    Complexity

    Time: O(n), where n is the number of employees. The loop visits each of the other n - 1 employees once and does a constant amount of work for each. Space: O(1). The program stores only bestIndex, i and bonus, however long the arrays are.

    Edge cases and common mistakes

    • Ties for the best score. With productivities 83, 150, 97, 150 and 120, employees 1 and 3 tie. The program prints Mary Jane, the earlier of the two, with a bonus of 50250. Using >= in the loop would move the best index to the later one and print Alice Chen.
    • One employee. The loop body never runs, bestIndex stays 0 and that employee is printed. A single employee named Solo with productivity 10 and salary 100000 gives Solo and Bonus: $15000.
    • Best employee first or last. If the best is at position 0, nobody ever beats it and bestIndex stays 0. If the best is last, the index only reaches it on the final turn. Both work.
    • Storing the value instead of the index. It finds the highest score but loses track of whose it is.
    • Starting the loop at 0. It works, because comparing employee 0 with itself is never strictly greater, but it does one pointless comparison.
    • An empty array. The code reads index 0 straight away, so it would throw IndexOutOfRangeException. The lesson's data always has employees.

    Testing

    • The starter data gives Alice Chen and Bonus: $37500.
    • Productivities 200, 133, 97, 150, 120 (best first) give John Doe and Bonus: $20250.
    • Productivities 1, 2, 3, 4, 5 (best last) give Carlos Diaz and Bonus: $27000.
    • Productivities 83, 150, 97, 150, 120 (tie) give Mary Jane and Bonus: $50250.
    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