Solved

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

Posted on 2011-10-09
235 Views
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

LVL 74

Assisted Solution

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

LVL 6

Accepted Solution

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 Closing Comment

0

## Featured Post

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.