The program I'm trying to write allows me to enter 10 numbers and it should get tell me Number X is repeated X times and so on.
I've been trying this but the problem is I get the result as follows:
For example...{1,1,1,1,4,6,4,7,4}
The number 1 is repeated 4 times
The number 1 is repeated 3 times
The number 1 is repeated 2 times
The number 1 is repeated 1 times
The number 4 is repeated 3 times
The number 6 is repeated 1 times
The number 4 is repeated 2 times
The number 7 is repeated 1 times
The number 4 is repeated 1 times
The problem is that it checks the next number with the following numbers without skipping it, or without knowing it has written it before
#include <iostream>
#include <string>
using namespace std;
int main() {
int x[10];
for (int i=0;i<10;i++) {
cin>>x[i];
}
for (int i=0;i<9;i++) {
int count=1;
for (int j=i+1;j<10;j++) {
if (x[i]==x[j]) count++;
}
cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
}
}
The most effective way I have recently come across with this...
OUTPUT:
Here's a fairly simple implementation using
std::map
.Output:
Compiled using the C++14 standard, but it should also work with C++11. Get rid of the vector initializer and use of
auto
and it should work with C++98.output is like this:
enter length of array:
6
enter element:6
enter element:5
enter element:5
enter element:6
enter element:2
enter element:3
2is repeat:1time
3is repeat:1time
5is repeat:2time
6is repeat:2time
The problem with your code is that you re-process numbers that you've already processed. So if there is an occurrence of
1
at position 0 and another occurrence of1
at position 5, then you will process the1
at position 5 again when you get there in the loop.So you need a way to decide if a number has been processed already or not. An easy way is to add a second array (initially all values are set to 0) and whenever you process a number you mark all positions where that element occurs. Now before processing an element you check if it's been processed already and do nothing if that's the case.
Also, try to indent your code properly :)
C++ Code:
Pretty simple using
map
!Expected output: