I'm trying to see which number occurs the most in an array. I wrote this code, but its not outputting the correct numbers. Could someone tell me where I am going wrong
My logic:
- It goes through the array to find numbers that are the same to itself. Then it adds +1 to each time it finds a number that is the same to itself (loop_freq_amt).
-
Then after it finishes the array it sees if the loop_freq_amt (the number's frequency it just checked) is greater than the current number which as the most frequency (freq_amt). If it is greater, then the freq_num gets replaced.
int most_freq(int num_array[], int total_numbers) { int freq_num = 0; int freq_amt = 0; int i = 0; while(i <= total_numbers) { int loop_freq_num = num_array[i]; int loop_freq_amt = 0; int j = 0; while(j <= total_numbers) { if (num_array[i] == num_array[j]) { loop_freq_amt += 1; } j++; } if(loop_freq_amt > freq_amt) { freq_num = loop_freq_num; } i++; } return freq_num;
}
Aucun commentaire:
Enregistrer un commentaire