C program to count numbers of even and odd elements in an array

Program to count the number of even and odd elements in an array

Here we will discuss the process of counting the number of even and odd elements in an array . Given an array of integers, count the total number of odd elements and even elements in the array and display them as output.

Example

  • Input – Arr[4]={1, 2, 3, 4}
  • Output-
  • Even elements-2
  • Odd elements- 2
count number of even and odd elements in an array in C

Algorithm :

 

  • Take the size of the array from the user and store it in a variable say N.
  • Declare an array of size N and named it say Arr[].
  • Take N integer input elements of the array from the user.
  • Declare two variable say count_even and count_odd that will count the even and odd elements respectively and initialize them with 1.
  • Run a loop from i=0 to N-1 and check if the ith element is even then increment the count_even by 1 and if it is odd then count_odd by 1.
  • After the execution of the entire loop print the value of count_even and count_odd.
count even and odd in C

Code in C :

#include<stdio.h>

int main(){

int N;
scanf("%d", &N);

int Arr[N], count_even =0, count_odd=0;

for(int i=0; i<N; i++)
scanf("%d", &Arr[i]);

for(int i=0; i<N; i++)
{
if(Arr[i]%2==0)
count_even++;

else
count_odd++;
}

printf("Even elements : %d\n", count_even);
printf("Odd elements : %d\n", count_odd);

return 0;
}
Input :

5

1 3 4 2 6

Output :

Even elements : 4

Odd elements : 1