Counting the Number of Even and Odd Elements in an Array in C++
Understanding Even and Odd Count
This task involves counting the number of even and odd elements in an array.
We will explore three different methods to achieve this in C++.
Method 1: Using Loop
This method iterates through the array and counts even and odd elements.
#include <iostream> using namespace std; void countEvenOdd(int arr[], int n) { int evenCount = 0, oddCount = 0; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) evenCount++; else oddCount++; } cout << "Even Count: " << evenCount << ", Odd Count: " << oddCount << endl; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); countEvenOdd(arr, n); return 0; }
Even Count: 4, Odd Count: 4
Method 2: Using Recursion
This method counts even and odd numbers using recursion.
#include <iostream> using namespace std; void countEvenOddRec(int arr[], int n, int index, int &evenCount, int &oddCount) { if (index == n) return; if (arr[index] % 2 == 0) evenCount++; else oddCount++; countEvenOddRec(arr, n, index + 1, evenCount, oddCount); } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); int evenCount = 0, oddCount = 0; countEvenOddRec(arr, n, 0, evenCount, oddCount); cout << "Even Count: " << evenCount << ", Odd Count: " << oddCount << endl; return 0; }
Even Count: 4, Odd Count: 4
Method 3: Using Bitwise Operations
This method uses bitwise operations to determine even and odd numbers.
#include <iostream> using namespace std; void countEvenOddBitwise(int arr[], int n) { int evenCount = 0, oddCount = 0; for (int i = 0; i < n; i++) { if ((arr[i] & 1) == 0) evenCount++; else oddCount++; } cout << "Even Count: " << evenCount << ", Odd Count: " << oddCount << endl; } int main() { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; int n = sizeof(arr) / sizeof(arr[0]); countEvenOddBitwise(arr, n); return 0; }
Even Count: 4, Odd Count: 4