Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Majority Element in an Array in C

Majority Element in array in C Language

 

In this page we will look into a coding question where we will learn how to find the element which occurs majority number of times in array in C Programming Language.
There might be different approach to solve this question, one you will find here. If your approach is bit different post it onto the comment section.

Majority Element in C

Problem Statement

Write a program in C programming language where you need to find the element of array which occurs most time in the array

Input Format
    -First line will contain the number of elements present in the array.
    -Second line will contain the elements of array

Output Format
   
-Output contain only line that contains the element which occurs most times in the array.

Sample Test Case : 1

Input
9
1 2 1 2 1 4 5 1 2

Output
1

Sample Test Case : 2

Input
8
11 22 33 44 55 66 77 44

Output
44

Program for finding the element that occurs most time in an array

#include <stdio.h> 
int main()
{
    int n;
    scanf("%d",&n);
    int array[n];
    int max = 0;
    int count;
  int maxelement;
  for(int i=0i<ni++)
    {
        scanf("%d",&array[i]);
    }
    for(int i=0i<ni++)
    {
        count++;
        for(int j=0j<nj++)
        {
            if(array[i]==array[j])
            {
                count++;
            }
        }
        if(count>max)
        {
            max = count;
            maxelement = array[i];
        }    
    }
    printf("%d",maxelement);
    return 0;
}

Learn About Arrays in C

Click on the below button to learn about in C Programming Language

Learn Arrays in C

Learn Data Structures

Click on the below button to study more Data Structure

Learn Data Structures