C Program to Count Occurrence of an Element in an Array

Write a C program to count occurrence of an element in an array using for loop.

#include <stdio.h>

int main()
{
	int Size, i, num, occr = 0;

	printf("Please Enter the Array size = ");
	scanf("%d", &Size);

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

	printf("Please Enter the Array Item to Know = ");
	scanf("%d", &num);

	for (i = 0; i < Size; i++)
	{
		if (arr[i] == num)
		{
			occr++;
		}
	}

	printf("%d Occurred %d Times.\n", num, occr);
}
C Program to Count Occurrence of an Element in an Array

C program to count the occurrence of an element in an array using a while loop.

#include <stdio.h>

int main()
{
	int Size, i, num, occr = 0;
	printf("Please Enter the size = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("Enter the %d elements : ", Size);
	i = 0;
	while (i < Size)
	{
		scanf("%d", &arr[i]);
		i++;
	}

	printf("Please Enter the Item to Know = ");
	scanf("%d", &num);

	i = 0;
	while (i < Size)
	{
		if (arr[i] == num)
		{
			occr++;
		}
		i++;
	}

	printf("%d Occurred %d Times.\n", num, occr);
}
Please Enter the size = 10
Enter the 10 elements : 2 22 33 2 44 2 55 7 2 90
Please Enter the Item to Know = 2
2 Occurred 4 Times.

In this C example, we removed the extra loop and counted the occurrence of the given array element within the do while loop.

#include <stdio.h>

int main()
{
	int Size, i, num, occr = 0;

	printf("Please Enter the Item to Know = ");
	scanf("%d", &num);

	printf("Please Enter the size = ");
	scanf("%d", &Size);

	int arr[Size];

	printf("Enter the %d elements : ", Size);
	i = 0;
	do
	{
		scanf("%d", &arr[i]);
		if (arr[i] == num)
		{
			occr++;
		}

	} while (++i < Size);

	printf("%d Occurred %d Times.\n", num, occr);
}
Please Enter the Item to Know = 50
Please Enter the size = 7
Enter the 7 elements : 50 90 120 50 70 50 100
50 Occurred 3 Times.

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.