OneBite.Dev - Coding blog in a bite size

Count The Number Of Occurrences Of A Specific Element In An Array In Dart

Code snippet for how to Count The Number Of Occurrences Of A Specific Element In An Array In Dart with sample and detail explanation

In the world of programming, understanding data structures and their manipulations is crucial. This article specifically focuses on determining the number of occurrences of a specific element in an array using Dart programming language.

Code snippet for Counting the Number of Occurrences of a Specific Element in an Array

Below is the simple Dart code snippet that counts the number of times a specific element appears in an array:

void main() {
    List<int> array = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
    int elementToFind = 3;
    int count = 0;
  
    for (int i=0; i<array.length; i++) {
        if (array[i] == elementToFind) {
            count++;
        }
    }
  
    print("$elementToFind appears $count times");
}

Now, let’s run this code. We will see ‘3 appears 3 times’ printed on the console.

Code Explanation for Counting the Number of Occurrences of a Specific Element in an Array

Let’s break down this code step by step to understand how it works:

  1. We start by defining our main function, void main(), which is the entry point for our programme.

  2. Inside our main function, we define array, a list of integers with random repeating numbers.

  3. We then declare an integer elementToFind and set it to 3. This is the element we want to find the occurrence of in the array.

  4. We underscore elementToFind with an initialized counter variable count that is set to zero. This variable keeps track of the number of times elementToFind appears in the array.

  5. Next, a for loop is used to traverse through the elements in the array from the first index 0 until the last index (array.length - 1).

  6. Inside the loop, we use an if statement to check if the current element matches elementToFind. If it matches, we increment count by 1 using count++.

  7. After looping through the entire array and incrementing count for each match, we print out our result with a statement that reads “X appears Y times” where X is the elementToFind and Y is the count.

This simple Dart program allows you to count the number of times a specific element appears in an array. By understanding this, you should be able to manipulate and analyze arrays effectively.

dart