• Status: Solved
• Priority: Medium
• Security: Public
• Views: 281

# how to search array for how many times a value has occurred c++

hello this sample program ask the user for 10 numbers, and then it ask the user for  a search number. after getting the search number it tells the user what index has the search number for example if user types in the values 1,5,7,7,4,5,6,9,10,11 and selects the search number 7 it will show the user where the search number are...Although i don't know how i can make the code so that it also tells the user how many times the search number has occurred  for example in 7 has occurred  2 times.. it should show "the search number occurred 2 times" ...need some help i have pasted my program below.

``````#include <iostream>
using namespace std;

int main(void)
{
int values[10];
int i;
int search_value;
cout <<"please enter 10 integer values:"<<endl;

for(i=1; i<=10;i++)
{
cout <<"#"<<i <<": ";

cin >> values[i-1];
}

cout <<"Please enter a search value: ";
cin >> search_value;

for(i = 0 ; i<10; i++)
{

if (search_value==values[i])
{
cout <<"found at index "  <<i <<endl;

}//end if statement

}//end for statement

//this should how many times the search value appeared in the array but i don't know how to code that...
cout <<"total occurrences of value " <<search_value <<"is" ;

}
``````
0
2 Solutions

Commented:
Maintain another integer variable and increment it each time your find a value (i.e. each time you display "xxx found at index..." At the end of your search loop, you can print the value of the new integer variable.
0

Commented:
See this code:
``````#include <iostream>
using namespace std;

int main(void)
{
int values[10];
int i;
int search_value;
int counter=0;
cout <<"please enter 10 integer values:"<<endl;

for(i=1; i<=10;i++)
{
cout <<"#"<<i <<": ";

cin >> values[i-1];
}

cout <<"Please enter a search value: ";
cin >> search_value;

for(i = 0 ; i<10; i++)
{

if (search_value==values[i])
{
counter++;

}//end if statement

}//end for statement

cout <<"total occurrences of value " << search_value << " is " << counter ;

}
``````
0

Author Commented: