Start learning free

LESSON 140 OF 347 · LOOPS & GLOBAL VARIABLES

Array Count in C#: Number of Occurrences with foreach

Practice Read the full explanation

Given an array of integers nums, count and return the number of occurrences of a given value.

Example:

Input: nums = [1, 4, 2, 2, 5, 2], value = 2
Output: 3
Explanation: the value 2 appears 3 times in the array

Note:

Do not use builtin functions, it would defy the purpose of the challenge. Write the whole code yourself.

STEP 1 OF 4
    Ctrl + Enter to check

    C# · LOOPS & GLOBAL VARIABLES

    Array Count in C#, explained

    Problem overview

    Count(int[] nums, int value) returns how many times value appears in nums. For nums = [1, 4, 2, 2, 5, 2] and value = 2, the number 2 appears three times, so the answer is 3.

    The lesson asks you to write the loop yourself rather than call a ready-made counting function, because the point is to practise the pattern.

    Approach: a counter that changes only on a match

    There is no way to know the count without looking at every element, so the method has to visit each one exactly once. While visiting, it keeps a counter. For every element, ask a single question: is it equal to value? If so, add one to the counter. If not, do nothing.

    Tracing the example, the counter goes 0, 0, 1, 2, 2, 3 as the loop passes 1, 4, 2, 2, 5, 2. When the loop ends, the counter holds the answer.

    This is the basic "count what matches" pattern. Variations of it, such as counting even numbers, counting words longer than three letters or counting values above a limit, only change the condition inside the if.

    Step by step

    1. Declare answer and set it to 0. It must exist before the loop, so that it keeps its value from one pass to the next. Zero is correct if nothing ever matches.
    2. Loop over the elements with foreach. foreach (int num in nums) gives each element in turn in the variable num. No index is needed, because only the values matter, not their positions.
    3. Compare and count. Inside the loop, if (num == value) checks the current element, and answer++ adds one to the counter when it matches. Elements that differ are skipped.
    4. Return after the loop. The return answer; line goes below the loop's closing brace. A return inside the loop would stop the method after the first element.

    The solution in C#

    class Solution {
        public int Count(int[] nums, int value) {
            int answer = 0;
            foreach (int num in nums) {
                if (num == value) {
                    answer++;
                }
            }
            return answer;
        }
    }
    

    A few C# points are worth noting:

    • == compares, = assigns. num == value asks a question. Writing num = value inside the if doesn't compile in C#, because an assignment to an int is not a bool. The compiler catches the typo for you.
    • answer++ adds one to answer. It is shorthand for answer = answer + 1.
    • foreach works on any collection. It handles arrays and lists in the same way. Use an index-based for loop only when you need the position of each element, as the next lessons do.
    • Arrays have a fixed length. nums.Length never changes, and the loop simply stops after the last element. An empty array is fine: the loop body doesn't run.

    Complexity

    Time: O(n). Each of the n elements is compared once, and each comparison and increment takes constant time. Every element has to be checked, so no counting method can do better on an unsorted array.

    Space: O(1). The method uses the counter and the loop variable only.

    Edge cases and common mistakes

    • The value is missing. The condition is never true, and the method returns 0.
    • An empty array. The loop doesn't run, and the method returns 0.
    • Every element matches. For [7, 7, 7] and value = 7 the answer is 3, the array's length.
    • Stopping at the first match. This is the mistake of using the pattern from the "find an index" lessons. A return inside the if would report 1 at most. For counting, the loop has to run to the end.
    • Declaring the counter inside the loop. The counter would be recreated at 0 on every pass, and the method would not compile at the final return, because answer would no longer be in scope there.
    • Forgetting the braces. Without braces an if controls only the next statement. It works for a single line, but adding a second line later is a classic source of bugs, so the braces are worth keeping.

    Testing

    • [1, 4, 2, 2, 5, 2] with value 2 gives 3.
    • [1, 2, 3] with value 9 gives 0.
    • [7, 7, 7] with value 7 gives 3.
    • [] with value 1 gives 0.
    • [-1, 1, -1] with value -1 gives 2.
    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