
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Frequency of a Number in an Array Using C++
Suppose we have an array. There are n different elements. We have to check the frequency of one element in the array. Suppose A = [5, 12, 26, 5, 3, 4, 15, 5, 8, 4], if we try to find the frequency of 5, it will be 3.
To solve this, we will scan the array from left, if the element is the same as the given number, increase the counter, otherwise go for the next element, until the array is exhausted.
Example
#include<iostream> using namespace std; int countElementInArr(int arr[], int n, int e) { int count = 0; for(int i = 0; i<n; i++){ if(arr[i] == e) count++; } return count; } int main () { int arr[] = {5, 12, 26, 5, 3, 4, 15, 5, 8, 4}; int n = sizeof(arr)/sizeof(arr[0]); int e = 5; cout << "Frequency of " << e << " in the array is: " << countElementInArr(arr, n, e); }
Output
Frequency of 5 in the array is: 3
Advertisements