Sunday, January 25, 2015

C++ Program for counting the frequency of a number in an array

#include<iostream>
using namespace std;
/*Function Prototype*/
int countFrequency(int arr[], int size, int value); //function for conunting how many times a number exists in an array

int main()
{
int array[50], //defining array of large size(50)
size,value,
occurance;
cout << "Enter the size of array(should be between 0to50): ";
cin >> size;
while(size<1||size>50) //testing if the size is not in the available range
{
cout << "Wrong Input(should be between 0to50)!"
<< "\nEnter again: ";
cin >> size;
}
cout << "Enter the array elements\n";
for( int i=0 ; i<size ; i++ ) //for getting input for individual elements
{
cout << "Enter the element "
<< (i+1)
<< ": ";
cin >> array[i]; //getting input for each element
}
cout << "Enter the value to find its frequency: ";
cin >> value;
occurance=countFrequency(array,size,value); //calling function by passing array , its size and value to be searched
if( occurance==0 ) //if the desired value dioes not exist
cout << "The number "
<< value
<< " does not exist in the array.\n";
else //if the desired value existed
{
cout << "The number "
<< value
<< " exists in the array "
<< occurance
<< " time(s).\n";
}

return 0;
}
/*Function Definition*/
int countFrequency(int arr[], int size, int value)
{
int occur=0;
for( int i=0 ; i<size ; i++ )
{
if(arr[i]==value) //testing each element
occur++; //calculating how many times the given number existed
}
return occur;
}

No comments:

Post a Comment