Write a program to Count Occurrence of Given Element in an Array in C
Write a program to Count Occurrence of Given Element in an Array in C++
Write a program to Count Occurrence of Given Element in an Array in Python
Write a program to Count Occurrence of Given Element in an Array in PHP
Write a program to Count Occurrence of Given Element in an Array in Java
Write a program to Count Occurrence of Given Element in an Array in Java Script
Write a program to Count Occurrence of Given Element in an Array in C#
Explanation:
Logic:
Initialize a Counter:
count = 0
Iterate Through the Array:
For each element in the array:
If the element matches the given element, increment the count.
Output:
After processing all elements, return or print the value of count.
Program to Count Occurrence of Given Element in an Array
C
C++
Python
PHP
JAVA
Java Script
C#
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 2, 5, 2}; // Example array
int size = sizeof(arr) / sizeof(arr[0]);
int element = 2; // Element to search for
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
count++;
}
}
printf("Element %d occurred %d times.\n", element, count);
return 0;
}
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 2, 5, 2}; // Example array
int size = sizeof(arr) / sizeof(arr[0]);
int element = 2; // Element to search for
int count = 0;
for (int i = 0; i < size; i++) {
if (arr[i] == element) {
count++;
}
}
cout << "Element " << element << " occurred " << count << " times." << endl;
return 0;
}
arr = [1, 2, 3, 2, 5, 2] # Example array
element = 2 # Element to search for
count = arr.count(element)
print(f"Element {element} occurred {count} times.")
<?php
$arr = array(1, 2, 3, 2, 5, 2); // Example array
$element = 2; // Element to search for
$count = 0;
foreach ($arr as $num) {
if ($num == $element) {
$count++;
}
}
echo "Element $element occurred $count times.\n";
?>
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 5, 2}; // Example array
int element = 2; // Element to search for
int count = 0;
for (int num : arr) {
if (num == element) {
count++;
}
}
System.out.println("Element " + element + " occurred " + count + " times.");
}
}
const arr = [1, 2, 3, 2, 5, 2]; // Example array
const element = 2; // Element to search for
const count = arr.filter(num => num === element).length;
console.log(`Element ${element} occurred ${count} times.`);
<div class="contain-inline-size rounded-md border-[0.5px] border-token-border-medium relative bg-token-sidebar-surface-primary dark:bg-gray-950"><div class="overflow-y-auto p-4" dir="ltr"><code class="!whitespace-pre hljs language-csharp">using System;
class Program {
static void Main() {
int[] arr = {1, 2, 3, 2, 5, 2}; // Example array
int element = 2; // Element to search for
int count = 0;
foreach (int num in arr) {
if (num == element) {
count++;
}
}
Console.WriteLine($"Element {element} occurred {count} times.");
}
}