#include <stdio.h>
int main() {
int n;
// Step 1: Read the size of the array
printf(“Enter the number of elements in the array: “);
if (scanf(“%d”, &n) != 1) {
printf(“Error reading input.\n”);
return 1;
}
int arr[n]; // Declare the array with user-defined size
// Step 2: Read the elements of the array
printf(“Enter %d elements:\n”, n);
for (int i = 0; i < n; i++) {
printf(“Element [%d]: “, i);
if (scanf(“%d”, &arr[i]) != 1) {
printf(“Error reading input.\n”);
return 1;
}
}
// Step 3: Count even and odd numbers
int evenCount = 0, oddCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
evenCount++; // Increment even counter
} else {
oddCount++; // Increment odd counter
}
}
// Step 4: Display the counts
printf(“\nNumber of even elements: %d\n”, evenCount);
printf(“Number of odd elements: %d\n”, oddCount);
return 0;
}
Explanation of the Program
- Input Array Size and Elements:
- The user inputs the size of the array and its elements.
- Count Even and Odd Numbers:
- A loop iterates through the array.
- Each element is checked using the condition
arr[i] % 2 == 0
:- If true, it’s an even number, and the
evenCount
is incremented. - Otherwise, it’s an odd number, and the
oddCount
is incremented.
- If true, it’s an even number, and the
- Display Results:
- The program prints the total counts of even and odd numbers.
Sample Input/Output
Input:
Enter the number of elements in the array: 6
Enter 6 elements:
Element [0]: 12
Element [1]: 7
Element [2]: 9
Element [3]: 4
Element [4]: 10
Element [5]: 3
Output:
Number of even elements: 3
Number of odd elements: 3