c++ - Count how many times elements in an array are repeated -
the program i'm trying write allows me enter 10 numbers , should tell me number x repeated x times , on.
i've been trying problem result follows:
for example...{1,1,1,1,4,6,4,7,4}
the number 1 repeated 4 times
the number 1 repeated 3 times
the number 1 repeated 2 times
the number 1 repeated 1 times
the number 4 repeated 3 times
the number 6 repeated 1 times
the number 4 repeated 2 times
the number 7 repeated 1 times
the number 4 repeated 1 times
the problem checks next number following numbers without skipping it, or without knowing has written before
#include <iostream> #include <string> using namespace std; int main() { int x[10]; (int i=0;i<10;i++) { cin>>x[i]; } (int i=0;i<9;i++) { int count=1; (int j=i+1;j<10;j++) { if (x[i]==x[j]) count++; } cout<<"the number "<<x[i]<<" repeated "<<count<<" times"<<"\n"; } }
the problem code re-process numbers you've processed. if there occurrence of 1
@ position 0 , occurrence of 1
@ position 5, process 1
@ position 5 again when there in loop.
so need way decide if number has been processed or not. easy way add second array (initially values set 0) , whenever process number mark positions element occurs. before processing element check if it's been processed , nothing if that's case.
also, try indent code :)
c++ code:
int main( void ) { const int n = 10; int a[n]; for(int = 0; < n; i++) cin >> a[i]; int seen[n]; for(int = 0; < n; i++) seen[i] = 0; for(int = 0; < n; i++) { if(seen[i] == 0) { int count = 0; for(int j = i; j < n; j++) if(a[j] == a[i]) { count += 1; seen[j] = 1; } cout << a[i] << " occurs " << count << " times" << endl; } } return 0; }
Comments
Post a Comment