Write a C program to print the frequency of elements in an array.
#include <stdio.h>
#define MAX 256
#define DUP 1
int main() {
int i, j, n, count, arr[MAX][2];
/* get the number of entries from the user */
printf("Enter the number of array elements:");
scanf("%d", &n);
/* get the array entries */
printf("Enter the array entries:\n");
for (i = 0; i < n; i++) {
printf("Array[%d]: ", i);
scanf("%d", &arr[i][0]);
arr[i][1] = 0;
}
/* find the frequency for each elements */
printf("\nElements Frequency\n");
for (i = 0; i < n; i++) {
count = 1;
if (arr[i][1])
continue;
for (j = i + 1; j < n; j++) {
if (arr[i][0] == arr[j][0]) {
arr[j][1] = DUP;
count++;
}
}
/* print the result */
printf("%d => %d\n", arr[i][0], count);
}
#define MAX 256
#define DUP 1
int main() {
int i, j, n, count, arr[MAX][2];
/* get the number of entries from the user */
printf("Enter the number of array elements:");
scanf("%d", &n);
/* get the array entries */
printf("Enter the array entries:\n");
for (i = 0; i < n; i++) {
printf("Array[%d]: ", i);
scanf("%d", &arr[i][0]);
arr[i][1] = 0;
}
/* find the frequency for each elements */
printf("\nElements Frequency\n");
for (i = 0; i < n; i++) {
count = 1;
if (arr[i][1])
continue;
for (j = i + 1; j < n; j++) {
if (arr[i][0] == arr[j][0]) {
arr[j][1] = DUP;
count++;
}
}
/* print the result */
printf("%d => %d\n", arr[i][0], count);
}
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the number of array elements:6
Enter the array entries:
Array[0]: 10
Array[1]: 20
Array[2]: 10
Array[3]: 20
Array[4]: 30
Array[5]: 10
Elements Frequency
10 => 3
20 => 2
30 => 1
Enter the number of array elements:6
Enter the array entries:
Array[0]: 10
Array[1]: 20
Array[2]: 10
Array[3]: 20
Array[4]: 30
Array[5]: 10
Elements Frequency
10 => 3
20 => 2
30 => 1
#include
ReplyDeleteint main()
{
int a[100];
int i, frequency[256] = {0},n;
printf("enter the size\n");
scanf("%d",&n);
printf("Enter a elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0; i<n ; i++)
{
frequency[a[i]]++;
}
printf("\nelements Frequency\n");
for(i=0; i < 256; i++)
{
if(frequency[i] != 0)
{
printf("%d%10d\n", i, frequency[i]);
}
}
return 0;
}