0

[c++] how to output unique elements from an array?

I just started to practice c++. So basically the should behave like this: cin - 1,1,2,3,3,4,4,5 cout- unique elements in the array are 2,5 however, code isn't working properly. I think it's happening because the condition is like arr[n]!=arr[a]. so it checks against every number. what would be the right approach here? Also, it'd be great if someone posted complete working code with explanation. thanks y'all. :) https://code.sololearn.com/cBCg5BoLkvlX/?ref=app

30th May 2017, 4:41 PM
anonymous
9 odpowiedzi
+ 6
It's your program a bit modified by me- #include <iostream> using namespace std; int main() { int a, n, arr[100], size, count; cout<<"Enter size of the array"<<endl; cin>>size; cout<<"Enter elements of the array"<<endl; for (n=0; n<size;n++){ cin>>arr[n]; } cout<<"The array you have entered is"<<endl; for (n=0;n<size;n++){ cout<<arr[n]; } cout<<endl; cout<<"Unique elements in the array are"<<endl; for(n=0;n<size;n++){ count=0; for(a=0;a<size;a++) { if(arr[n]==arr[a]) count++; } if(count==1) cout<<arr[n]; } return 0; }
30th May 2017, 5:51 PM
Sachin Artani
Sachin Artani - avatar
+ 4
Welcome anonymous 😁
30th May 2017, 5:57 PM
Sachin Artani
Sachin Artani - avatar
+ 4
Ofcourse, count variable is used to count the number of occurences of a number in the entire array. for each value of array, an inner loop is running. In inner loop, we are checking the occurence of a number, and at the end of the inner loop and the end of each iteration of the outer loop, we are checking, if the occurence (count) is 1, then print it, else do nothing. And at the beginning of each iteration of outer loop, we are initialising count by 0, because count should count from 0 🙂 Get it?
30th May 2017, 6:11 PM
Sachin Artani
Sachin Artani - avatar
+ 4
Yes, count will be initialised with the number of occurences, but what about the next number? We have to check every number with the total number occurences, so we have to set count to 0 every time for every new number in the array.
30th May 2017, 6:26 PM
Sachin Artani
Sachin Artani - avatar
+ 3
🙂
30th May 2017, 6:29 PM
Sachin Artani
Sachin Artani - avatar
+ 1
@sachin thanks alottt, mate
30th May 2017, 5:57 PM
anonymous
+ 1
@sachin I'm not getting the "count" part. can you please explain it?
30th May 2017, 6:01 PM
anonymous
+ 1
@sachin makes sense :) you're awesome lol. just one more question, what's​ the meaning of count=0 here? and does count++ mean that count will go like 0+1,1+1?
30th May 2017, 6:21 PM
anonymous
+ 1
@sachin gotcha :) thanks alot. :)
30th May 2017, 6:28 PM
anonymous