Program to find the number of occurrences of each value in an array.
#include <stdio.h>
// Program to find the number of occurrences of each value in an array.
// Assume you have an array with values -25 to +25.
#define MIN -25
#define MAX 25
void main(){
int grades[] = {20, 18, 20, -3 , 20, -5, -3, 3, 18, 20, -5, -25};
int arrSize = sizeof(grades) / sizeof(int);
int histo[MAX-MIN+1];
// number 5 appears 2 times; -3: 2 times; 3: 1 time; 18: 2 times ; 20: 4 times; -25: 1
// BAD SOLUTION: for each value scan the array. If n values and an array of size m
// you do n times m steps.
// GOOD SOLUTION: indexing
for (int i = 0; i< (MAX-MIN+1); ++i) histo[i]=0; // Initializing the histogram array.
for (i = 0;i< arrSize; ++i) histo[grades[i] - MIN] ++ ;
for (i = 0; i< (MAX-MIN+1); ++i)
if (histo[i]) printf("The value \t%4d appears %4d times.\n", i+MIN, histo[i]);
}