Description
Mode is a value which occur most frequently in a array. Ex: arr[] = {3,6,2,3,7} Mode will be 3 as it's frequency is 2 which is greatest in this array.
C/C++
/* C Program to Find Mode of a Array */ //Save it as ModeArray.c #include<stdio.h> int main(){ int i, j, n; printf("Enter the size of array : "); scanf("%d",&n); int arr[n]; printf("Enter the elements of array : "); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } printf("Entered elements are : "); for(i=0;i<n;i++) { printf("%d ",arr[i]); } int maxVal=0, count=0, maxCount=0; for(i=0;i<n;i++) { count = 0; for(j=0;j<n;j++) { if(arr[i] == arr[j]) { count++; } } if (count > maxCount) { maxCount = count; maxVal = arr[i]; } } printf("\nThe mode is : %d as count is : %d",maxVal,maxCount); return 0; }
Input: Enter the size of array : 5 Enter the elements of array : 3 6 2 3 7 Output: Entered elements are : 3 6 2 3 7 The mode is : 3 as count is : 2
Java
/* Java Program to Find Mode of a Array */ //Save it as ModeArray.java import java.io.*; import java.util.Scanner; public class ModeArray { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter the size of array : "); int n = scanner.nextInt(); int arr[] = new int[n]; System.out.println("Enter the elements of array : "); for(int i=0;i<n;i++) { arr[i] = scanner.nextInt(); } System.out.println("Entered elements are : "); for(int i=0;i<n;i++) { System.out.print(arr[i]+" "); } int maxVal=0, count=0, maxCount=0; for(int i=0;i<n;i++) { count = 0; for(int j=0;j<n;j++) { if(arr[i] == arr[j]) { count++; } } if (count > maxCount) { maxCount = count; maxVal = arr[i]; } } System.out.println("\nThe mode is : "+maxVal+" as count is : "+maxCount); } }
Input: Enter the size of array : 5 Enter the elements of array : 3 6 2 3 7 Output: Entered elements are : 3 6 2 3 7 The mode is : 3 as count is : 2
Related Programs
1) Program to Find Median of a Array2) Find the Average of Elements of Array
3) Find Smallest element and it’s position of an Array
4) Program for finding Second Largest Element Of Array
5) Program to form a number using entered digits
6) Program to insert a number at given position of an Array
7) Insert a number in an array sorted in ascending order
8) Program to delete an element from an array sorted in ascending order
9) Program to Reverse an Array using Recursion
10) Program to Find Value equal to index value
11) Program to Check Array is Perfect or Not
12) Remove Duplicate Elements From Array