Learn More Way

Problem :

Count Frequency of Each Element in an Array

Count Frequency of Each Element in an Array

যা শিখবো:

ধাপে ধাপে ব্যাখ্যা:

Step 1: ইউজার থেকে array size ও elements ইনপুট নেওয়া

C
scanf("%d", &n);
for(i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

Step 2: প্রতিটি element-এর জন্য frequency count করা

C
for(i = 0; i < n; i++) {
    if(visited[i] == 1)
        continue;

    count = 1;
    for(j = i + 1; j < n; j++) {
        if(arr[i] == arr[j]) {
            count++;
            visited[j] = 1; // same element পুনরায় গোনা হবে না
        }
    }

    printf("%d occurs %d times\n", arr[i], count);
}

উদাহরণ:

C
#include <stdio.h>

int main() {
    int arr[100], visited[100] = {0};
    int n, i, j, count;

    printf("Enter the number of elements: ");
    scanf("%d", &n);

    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    printf("\nFrequency of each element:\n");
    for(i = 0; i < n; i++) {
        if(visited[i] == 1)
            continue;

        count = 1;
        for(j = i + 1; j < n; j++) {
            if(arr[i] == arr[j]) {
                count++;
                visited[j] = 1;
            }
        }

        printf("%d occurs %d times\n", arr[i], count);
    }

    return 0;
}

আউটপুট উদাহরণ:

উদাহরণ ১:

C
Enter the number of elements: 7
Enter 7 elements:
1 2 2 3 1 4 2

Frequency of each element:
1 occurs 2 times
2 occurs 3 times
3 occurs 1 times
4 occurs 1 times

উদাহরণ ২:

C
Enter the number of elements: 5
Enter 5 elements:
5 5 5 5 5

Frequency of each element:
5 occurs 5 times

ব্যাখ্যা:

©2025 Linux Bangla | Developed & Maintaind by Linux Bangla.