Finding Mode Value From Array C Programming

In previous posts we learned how to find mean value from array and median value from array. In this post we will learn how to find mode value from array elements. Mode value is the most repeated value from the elements. In following simple program we will create a function which will accept an array as an input. Furthermore that function will return mode value from the array elements.

[js]

#include <stdio.h>

int mode(int arr[], int size); // function prototype

int main(void){

int arrayName[10] = {2,4,4,4,1,2,3,4,2,3}; // defined an array with 10 elements

//output each element of array
printf("Original values of the arraynn");
printf("Array indextttValuen");
for(int j=0; j<10; j++){
printf("%11dttt%4dn", j, arrayName[j]);
}

int a = mode(arrayName, 10); // function call

printf("nnMode Value is: %d", a);

return 0;
}

//function definition
int mode(int arr[], int size){
int freq[size] = {0};
for(int i=0; i<size; i++){
freq[arr[i]]++;
}

printf("nFrequency of each array elementnn");
printf("Array indextttValuen");
for(int j=0; j<10; j++){
printf("%11dttt%4dn", j, freq[j]);
}
int largest = 0;
for (int j=0; j<size; j++){
if(freq[j]>freq[largest]){
largest = j;
}
}

printf("nFrequency of each array element (graphical representation)nn");
printf("Array indextttFrequencyn");
for(int i=0; i<size; i++){
printf("%11dttt",i);
for(int j=0; j<freq[i]; j++){
printf("*");
}
printf("n");
}
return largest;
}

[/js]

Output:

Leave a Comment

Your email address will not be published.