There is an arbitrary array in which you need to sort the repeating elements by decrease and output the total number of repetitions. I decided to implement it in the following way: first, just sort the array using the bubble method, then cycle out the condition for matches, and if they are there, simply display them on the screen and add +1 to the match counter, thus avoiding the re-creation of the array. Wrote the following code:

#include <stdio.h> #include <conio.h> #define MAX 50 main(){ int array[MAX], n, i, j, tmp, repeat; printf("Number of elements array = "); scanf("%i",&n); printf("Type array elements:\n"); for(i=0; i<n; i++){ printf("Array[%i] = ",i); scanf("%i",&array[i]); if(array[i]==0) break; } for(i=0; i<n; i++){ tmp = 0; for(j=(i+1); j<n; j++){ if(array[i] < array[j]){ tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } } printf("The result of sorting:\n"); for(i=0; i<n; i++){ printf("%i\t",array[i]); } printf("\nRepeated elements:\n"); for(i=0,tmp=0; i<n; i++){ for(j=(i+1); j<n; j++){ if(array[i] == array[j]){ tmp++; printf("%i\t%i\t",array[i],array[j]); } } } if(tmp > 0){ printf("\nThe number of repetitions: %i",tmp); } else printf("\nThe array elements is not repeated"); getch(); return 0; } 

As you might have guessed, the comparison algorithm does not work correctly, namely: Screen of the running program

  • Your algorithm displays what you describe in it! You have two cycles, and the element of the first is compared with each element of the second, therefore you get 2 sixes, 2 fives and so many fours. And what exactly do you need to get at the exit? Just a list of duplicate numbers: 6,5,4? And another question, if the array has three "4" - is it counted as two repetitions (tmp + 2) or as one? - Rams666
  • For example, in the array of numbers 4,5,6,8,4,6,8,8,7,5. In the end, the screen should display: 8,8,8,6,6,5,5,4,4 and repetitions 5. That is, 6 is repeated once, 5 once, 4 once and 8 twice. - deeplulz
  • It is better to use standard built-in sorting functions. In C ++, it is preferable to use the STL sort () pattern. Using it is easy. - skegg

2 answers 2

  printf("\nRepeated elements:\n"); for(i=0,tmp=0; i<n-1; i++){ if (array[i]==array[i+1]) { printf("%i\t",array[i]); for(j=(i+1); j<n && array[j]==array[i]; j++){ tmp++; printf("%i\t",array[j]); } i=j-1; } } 

    Recently wrote a similar program, only without sorting

     #include <iostream> using namespace std; int main() { int arr[10],i,y,c, e, b,n=0,sum=0, arr2[10]; cout<<"Vvedite 10 chisel:\n"; //Заполняем массив for (i=0; i<10; i++) { cin>>arr[i]; } cout<<"Chisla:\n"; for (i=0; i<10; i++) { y= arr[i]; for (c=i+1; c<10; c++) { e=arr[c]; if (y==e) { sum+=1; } } if (sum>0) { for (b=0; b<10; b++) { if (arr2[b]==arr[i]) break; else { if (b==9) { arr2[n]=arr[i]; n++; break; } } } } sum=0; } for (i=0; i<=n-1; i++) { cout<<arr2[i]; } cout<<"\n"; system ("PAUSE"); return 0; }