### comparing elements of an array

Can someone help me to read how many times an element appeared in an array of numbers, for example int array[]= {1,1,2,3,4,1,3,2,9,8,7}
How can i display how many times each number appeared in the array of numbers.
Thanks....!
Use a range based for loop. After every time it encounters the literal you want to know how many times appeared use a if to increment a variable named count. Here is an example

 ``1234567891011`` ``````#include using namespace std; int main() { int count = 0; int array[]= {1,1,2,3,4,1,3,2,9,8,7}; for (int i:array) {if (i == 1) ++count;} cout<<"Number 1 appeared "<
Last edited on
This one allows you to choose

 ``12345678910111213`` ``````#include using namespace std; int main() { int num, count = 0; int array[]= {1,1,2,3,4,1,3,2,9,8,7}; cout<<"Which number would you like to know about how many times it appeared?"<>num; for (int i:array) {if (i == num) ++count;} cout<<"Number "<
Last edited on
 @Anmol444 using a range based loop

When i run that code in Code::Blocks, it says "error: range based-for-loops are not allowed in C++98 mode". Can you please tell what's wrong?
Range based for loops were a addition in c++ 11. It seems like your compiler settings are changed. Google how to change code::blocks to c++ 11 mode.

Here check this out: http://forums.codeblocks.org/index.php?topic=15536.0
http://stackoverflow.com/questions/6528595/how-can-i-get-codeblocks-to-compile-with-std-c0x-with-gcc
Last edited on
C++ has a function called count(), which does this:

 ``1234567891011`` ``````#include #include #include using namespace std; int main() { int array[]= {1,1,2,3,4,1,3,2,9,8,7}; int num = 1; unsigned int cnt = count(begin(array), end(array), num); cout << "The number " << num << " appears " << cnt << " times\n"; }``````

online demo: http://ideone.com/zztUtO

(if your compiler is too old to support begin/end for arrays, you can call count as `count(array, array + 11, num);`, where 11 is the number of elements in the array)
This should solve your problem:

Look in Project's "Build" properties, you'll see configurations tab for the compiler. Then select all the configurations, go in the list of features and select "C++0x".

Last edited on
 @Anmol

So the codes in codeblocks and VS 2012 are the same?Thanks once again.
No problem.
@Anmol
thanks... but if you dont mind another question, what if you have to read n compare the elements of the array from an infile?
Not quite sure on how to do that. Sorry
Topic archived. No new replies allowed.