C Program to find the count of even and odd elements in the array
Last updated on September 23, 2020
The following is a C program to count even and odd elements in the array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /***************************************************************
Program to find the count of even or odd elements in the array
***************************************************************/
#include<stdio.h> // include stdio.h library
#define MAX 5
int main(void)
{
int arr[MAX] = {1, 5, 9, 14, 200};
int even_count = 0, odd_count = 0; // variables to store even or odd count
// iterate over the arrays
for(int i = 0; i < MAX; i++)
{
// check for even number
if(arr[i] % 2 == 0)
{
even_count++;
}
else
{
odd_count++;
}
}
printf("Even elements = %d\n", even_count);
printf("Odd elements = %d", odd_count);
return 0; // return 0 to operating system
}
|
Expected Output:
1 2 | Even elements = 2
Odd elements = 3
|
How it works #
- In line 10, we declare and initialize an array named
arr
. - In line 11, we declare and initialize variables
even_count
andodd_count
, to store the count of even and odd elements respectively. - In line 14-27, we have for loop to iterate over the items in the array.
- In line 17, we have an if statement to check for even number. If the condition evaluates to true, we increment the
even_count
by 1. Otherwise, the element is odd and we increment theodd_count
by 1. The for loop terminates when we run out of elements in the array. - In lines 28 and 29, we print the value of
even_count
andodd_count
using the print statement.
Recommended Reading:
Load Comments