Write a c program to count the nagative numbers in an array code example
Example 1: c program to count frequency of each element in an array
/**
* C program to count frequency of each element of array
*/
#include <stdio.h>
int main()
{
int arr[100], freq[100];
int size, i, j, count;
/* Input size of array */
printf("Enter size of array: ");
scanf("%d", &size);
/* Input elements in array */
printf("Enter elements in array: ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
/* Initially initialize frequencies to -1 */
freq[i] = -1;
}
for(i=0; i<size; i++)
{
count = 1;
for(j=i+1; j<size; j++)
{
/* If duplicate element is found */
if(arr[i]==arr[j])
{
count++;
/* Make sure not to count frequency of same element again */
freq[j] = 0;
}
}
/* If frequency of current element is not counted */
if(freq[i] != 0)
{
freq[i] = count;
}
}
/*
* Print frequency of each element
*/
printf("\nFrequency of all elements of array : \n");
for(i=0; i<size; i++)
{
if(freq[i] != 0)
{
printf("%d occurs %d times\n", arr[i], freq[i]);
}
}
return 0;
}
Example 2: Write a C program to count total number of duplicate elements in an array.
/**
* C program to count total number of duplicate elements in an array
*/
#include <stdio.h>
#define MAX_SIZE 100 // Maximum array size
int main()
{
int arr[MAX_SIZE];
int i, j, size, count = 0;
/* Input size of array */
printf("Enter size of the array : ");
scanf("%d", &size);
/* Input elements in array */
printf("Enter elements in array : ");
for(i=0; i<size; i++)
{
scanf("%d", &arr[i]);
}
/*
* Find all duplicate elements in array
*/
for(i=0; i<size; i++)
{
for(j=i+1; j<size; j++)
{
/* If duplicate found then increment count by 1 */
if(arr[i] == arr[j])
{
count++;
break;
}
}
}
printf("\nTotal number of duplicate elements found in array = %d", count);
return 0;
}