Open In App

How to Count the Number of Occurrences of a Value in an Array in C++?

Last Updated : 18 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, an array is a data structure that stores the collection of the same type of data in a contiguous memory location. In this article, we will learn how to count the number of occurrences of a value in an array in C++.

Example:

Input: 
arr= {2, 4, 5 ,2 ,4 , 5, 2 , 3 ,8}
Target = 2

Output:
Number of occurences of 2 are : 3

Count the Number of Occurrences in an Array in C++

To count the number of occurrences of a specific value in an array, we can use a simple for loop while looking for our target value. If the target value is found, we increment the counter variable. We do this till the whole array is scanned.

Approach

  • Initialize a counter variable set to zero.
  • Iterate through the array and check if the current element matches the target value.
  • If it matches, increment the counter by one.
  • Else continue to the next iteration.
  • Repeat the process until all elements in the array have been checked.
  • Finally, return the counter.

C++ Program to Count the Number of Occurrences of a Value in an Array

The below example demonstrates how we can count the total number of occurrences of a value in an array.


Output
Number 2 occurs 3 times in the array.

Time Complexity: O(n), here n is the number of elements in the array.
Auxilliary Space: O(1)


Next Article
Practice Tags :

Similar Reads