C Online Compiler
Example: Count Frequency with Visited Marker in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Count Frequency with Visited Marker #include
int main() { // Step 1: Initialize the array and its size int arr[] = {1, 2, 8, 3, 2, 2, 2, 5, 1}; int n = sizeof(arr) / sizeof(arr[0]); // Step 2: Declare a frequency array of the same size, initialized to 0 int freq[n]; for (int i = 0; i < n; i++) { freq[i] = 0; } // Step 3: Iterate through the array to count frequencies for (int i = 0; i < n; i++) { int count = 1; // Start count for the current element // If the element hasn't been counted yet if (arr[i] != -1) { // Compare it with subsequent elements for (int j = i + 1; j < n; j++) { if (arr[i] == arr[j]) { count++; freq[j] = -1; // Mark element as visited by setting its freq to -1 } } freq[i] = count; // Store the frequency of the current element } } // Step 4: Print the frequencies of unique elements printf("Element | Frequency\n"); printf("--------|-----------\n"); for (int i = 0; i < n; i++) { if (freq[i] != -1) { // Only print if the element was not a duplicate printf("%7d | %9d\n", arr[i], freq[i]); } } return 0; }
Output
Clear
ADVERTISEMENTS