Description
Get an array as input from the user and find the frequency of each element in that array.
Input
Enter the size of array
3
Enter the elements
1 2 1
Output
1 occurs 2 times
2 occurs 1 times
C Program
#include<stdio.h>
int main()
{
int n;
int arr[n];
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the elements of array: ");
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
int visit[n];
for(int i=0; i<n; i++){
if(visit[i]!=1){
int count = 1;
for(int j=i+1; j<n; j++){
if(arr[i]==arr[j]){
count++;
visit[j]=1;
}
}
printf("%d occurs %d times\n", arr[i], count);
}
}
return 0;
}
C++ Program
#include <iostream>
using namespace std;
int main()
{
int n;
printf("Enter the size of array: ");
scanf("%d",&n);
int arr[n];
printf("Enter the array elements: ");
for(int i=0;i<n;i++)
scanf("%d",&arr[i]);
int visit[n];
for(int i=0; i<n; i++){
if(visit[i]!=1){
int count = 1;
for(int j=i+1; j<n; j++){
if(arr[i]==arr[j]){
count++;
visit[j]=1;
}
}
cout<<arr[i]<<" occurs at "<<count<<" times "<<endl;
}
}
return 0;
}
Java Program
import java.util.Arrays;
import java.util.Scanner;
class Main
{
public static void countFrequency(int arr[], int n)
{
boolean visit[] = new boolean[n];
Arrays.fill(visit, false);
for (int i = 0; i < n; i++) {
if (visit[i] == true)
continue;
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
visit[j] = true;
count++;
}
}
System.out.println(arr[i] + " occurs " + count +" times ");
}
}
public static void main(String []args)
{
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array: ");
n = sc.nextInt();
int[]arr = new int[n];
System.out.println("Enter the array elements: ");
for(int i = 0; i < n; i++)
{
arr[i] = sc.nextInt();
}
countFrequency(arr, n);
}
}
Python Program
def countFrequency(arr, n):
visit = [False for i in range(n)]
for i in range(n):
if (visit[i] == True):
continue
count = 1
for j in range(i + 1, n, 1):
if (arr[i] == arr[j]):
visit[j] = True
count += 1
print(arr[i]," occurs ",count," times ")
n = int(input("Enter size of array: "))
arr = []
print("Enter array elements: ")
for i in range(0,n):
temp = int(input())
arr.append(temp)
countFrequency(arr, n)