Frequency of Elements in Array in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Frequency of Each Element in Array in C: Program to Find Occurrence of Elements

šŸ“‘ On this page:
  • Introduction
  • C Program to Find Frequency
  • Sample Output
  • Program Explanation
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • How to find the frequency of each element in an array
  • How to use a visited array to avoid counting duplicates
  • How to display element-wise frequency counts
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to find the frequency or occurrence of each element in an array.

Finding the frequency of elements in an array is a common programming task. It is used in many real-world applications, such as:

  • Finding the most frequent number in a dataset
  • Analyzing survey responses
  • Counting word occurrences in text processing
  • Identifying duplicate values in a list

šŸ’” Key Point: Frequency of an element is the number of times it appears in the array. To avoid counting the same element multiple times, we use a visited array to mark elements that have already been counted.

C Program to Find Frequency of Each Element in Array

#include <stdio.h>

int main() {
    int n, i, j;
    int count;
    
    // Ask user for number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    // Declare array of size n
    int arr[n];
    // Declare visited array to track counted elements
    int visited[n];
    
    // Initialize visited array with 0
    for(i = 0; i < n; i++) {
        visited[i] = 0;
    }
    
    // Read elements into the array
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Find frequency of each element
    printf("\nFrequency of each element:\n");
    for(i = 0; i < n; i++) {
        // Skip if element is already counted
        if(visited[i] == 1) {
            continue;
        }
        
        count = 1;
        for(j = i + 1; j < n; j++) {
            if(arr[i] == arr[j]) {
                count++;
                visited[j] = 1;  // Mark as visited
            }
        }
        
        printf("%d occurs %d times\n", arr[i], count);
    }
    
    return 0;
}

Sample Output

Enter the number of elements: 8
Enter 8 elements:
10 20 30 10 20 10 40 30

Frequency of each element:
10 occurs 3 times
20 occurs 2 times
30 occurs 2 times
40 occurs 1 times

Another Example:

Enter the number of elements: 6
Enter 6 elements:
5 5 5 5 5 5

Frequency of each element:
5 occurs 6 times

Example with Negative Numbers:

Enter the number of elements: 7
Enter 7 elements:
-5 10 -5 20 -5 10 30

Frequency of each element:
-5 occurs 3 times
10 occurs 2 times
20 occurs 1 times
30 occurs 1 times

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int n; — stores the number of elements
    • int i, j; — loop counters
    • int count; — stores the frequency of each element
  3. Declare Arrays:
    • int arr[n]; — the main array
    • int visited[n]; — keeps track of elements that have already been counted
  4. Initialize Visited Array: The for loop sets all elements of visited to 0 (not counted yet).
  5. Get User Input: Prompts the user to enter the number of elements and then reads them into the array.
  6. Find Frequency: The outer loop for(i = 0; i < n; i++) iterates through each element:
    • If visited[i] == 1, the element has already been counted, so skip it.
    • Otherwise, set count = 1 and compare arr[i] with all later elements using the inner loop.
    • If a match is found, increment count and mark visited[j] = 1.
  7. Display Result: Prints each unique element and its frequency.
  8. Return: return 0; indicates successful program execution.

šŸ“ Why Use a Visited Array? Without a visited array, the program would print the frequency of duplicate elements multiple times. For example, if 10 appears three times, it would print "10 occurs 3 times" three times. The visited array ensures each element is printed only once.

Algorithm to Find Frequency of Elements

  1. Start
  2. Read the number of elements (n)
  3. Read n elements into the array arr
  4. Initialize visited array with 0
  5. For i = 0 to n-1:
    • If visited[i] == 0:
      • Set count = 1
      • For j = i+1 to n-1:
        • If arr[i] == arr[j]:
          • count++
          • Set visited[j] = 1
      • Print arr[i] and count
  6. End

Alternative Method: Using Sorting

Another approach to find frequency is to sort the array first, then count consecutive equal elements. This method can be more efficient for large arrays.

#include <stdio.h>

int main() {
    int n, i, j, count;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    // Simple bubble sort to sort the array
    for(i = 0; i < n-1; i++) {
        for(j = 0; j < n-i-1; j++) {
            if(arr[j] > arr[j+1]) {
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    
    // Count frequency of each element
    printf("\nFrequency of each element:\n");
    for(i = 0; i < n; i = i + count) {
        count = 1;
        for(j = i + 1; j < n && arr[j] == arr[i]; j++) {
            count++;
        }
        printf("%d occurs %d times\n", arr[i], count);
    }
    
    return 0;
}

šŸ’» Practice Exercise

Challenge 1: Modify the program to find and display only the most frequent element in the array.

Challenge 2: Find the unique elements (elements that appear exactly once) in the array.

šŸ” Click to Show Solution for Challenge 1
#include <stdio.h>

int main() {
    int n, i, j;
    int max_freq = 0, most_frequent_element;
    
    printf("Enter the number of elements: ");
    scanf("%d", &n);
    
    int arr[n];
    int visited[n];
    
    for(i = 0; i < n; i++) {
        visited[i] = 0;
    }
    
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }
    
    for(i = 0; i < n; i++) {
        if(visited[i] == 1) {
            continue;
        }
        
        int count = 1;
        for(j = i + 1; j < n; j++) {
            if(arr[i] == arr[j]) {
                count++;
                visited[j] = 1;
            }
        }
        
        if(count > max_freq) {
            max_freq = count;
            most_frequent_element = arr[i];
        }
    }
    
    printf("\nMost frequent element: %d (appears %d times)\n", 
           most_frequent_element, max_freq);
    
    return 0;
}

Frequently Asked Questions

1. How do you find the frequency of elements in an array in C?

Use a visited array to track counted elements. For each unvisited element, count how many times it appears by comparing it with all other elements. Display the element and its count.

2. Why do we need a visited array?

Without a visited array, duplicate elements would be printed multiple times. The visited array ensures that each element is counted and printed only once.

3. What is the time complexity of this approach?

The time complexity is O(n²) because we use nested loops to compare each element with every other element. The space complexity is O(n) for the visited array.

4. Is there a faster way to find frequency?

Yes, you can sort the array first and then count consecutive equal elements. This has a time complexity of O(n log n) due to sorting. For integer ranges with limited values, you can also use a hash table or frequency array.

5. How can I find the frequency of a specific element?

Simply iterate through the array and count how many times that specific element appears. You don't need a visited array for a single element.

šŸ’” Tip: For large arrays with a small range of values, consider using a frequency array where the index represents the value and the value at that index represents the frequency.

šŸ“– Related Tutorials

  • Print Negative Elements in Array
  • Reverse an Array in C
  • Remove Duplicate Elements from Array
  • More Array Assignments

Previous Topic: -->> Print Negative Elements in Array   ||   Next topic: -->> Reverse an Array in C


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.