C++ program to count occurrences of an array element


C++ program to count occurrences of an array element 

        In this program, you will be counting how many times any particular element occurs in an array. Take all the inputs from the user, set the counter to zero. Traverse through the array and check the element matches with the given element or not. If the match is found increase the counter. Finally, print the counter. 


Code

#include <bits/stdc++.h>

using namespace std;


int main() {

    int n;                                                                 //array size

    cin>>n;

    

    int a[n];                                                    //array declaration

    

    for(int i=0;i<n;i++){                            //reading the array elements

        cin>>a[i];

    }

    

    cout<<"Enter any element"<<endl;

    

    int s;                                                                     //to store given element

    cin>>s;

    

    int c=0;                                                             //set counter to zero

    

    for(int i=0;i<n;i++){                                //traversing the array

        if(a[i]==s){                                        //if match found increase counter

            c++;

        }

    }

    

    cout<<s<<" occurred "<<c<<" times";     //print the no of occurrences

    

    return 0;

}


Input

5

2 4 2 9 2


Output

Enter any element

2

2 occurred 3 times


Post a Comment

0 Comments