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
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace 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 "<<count<<" times in the array"<<endl;
return 0;
}
#include <iostream>
usingnamespace 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?"<<endl;
cin>>num;
for (int i:array)
{if (i == num) ++count;}
cout<<"Number "<<num<<" appeared "<<count<<" times in the array"<<endl;
return 0;
}
(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)
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".