From a set of array elements, find the number of occurrences of each element present in the given array.
Input :
5
2
4
2
5
Output:
2 occurs 2 time
4 occurs 1 time
5 occurs 2 time
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void selectionSort(int numbers[],int size) {
int i, j, indexmin;
for(i = 0; i<size-1; i++) {
indexmin = i;
for(j = i+1; j<size; j++)
if(numbers[j] < numbers[indexmin])
indexmin = j;
int temp;
temp = numbers[i];
numbers[i] = numbers[indexmin];
numbers[indexmin] = temp;
}
}
int main() {
int numbers[1000];
int usedNumbers[12];
int i=0,j;
int times = 0;
int usedNumbersCounter = 0;
int occurs=0;
char input[10];
int totalNumberOfNumbers=0;
//Loop until empty line
while(1){
gets(input);
if (strcmp(input, "\0") == 0){
break;
}else{
numbers[totalNumberOfNumbers]=atoi(input);
totalNumberOfNumbers++;
}
}
//sort values
selectionSort(numbers,totalNumberOfNumbers);
for (i=0; i<totalNumberOfNumbers; i++){
times = 0;
for (j=0; j<totalNumberOfNumbers; j++){
if (numbers[i] == numbers[j]){
times++;
}
}
occurs=0;
for (j=0; j<totalNumberOfNumbers; j++){
if (numbers[i] == usedNumbers[j]){
occurs=1;
break;
}
}
if(occurs==0){
printf("%d occurs %d time\n",numbers[i],times);
usedNumbers[usedNumbersCounter]=numbers[i];
usedNumbersCounter++;
}
}
getchar();
getchar();
return 0;
}
Comments
Leave a comment