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:
-
We start by defining our main function,
void main()
, which is the entry point for our programme. -
Inside our main function, we define
array
, a list of integers with random repeating numbers. -
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. -
We underscore
elementToFind
with an initialized counter variablecount
that is set to zero. This variable keeps track of the number of timeselementToFind
appears in the array. -
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)
. -
Inside the loop, we use an
if
statement to check if the current element matcheselementToFind
. If it matches, we incrementcount
by 1 usingcount++
. -
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 thecount
.
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.