Count number of Even element and Odd elements of the Array

ā€œCount number of Even element and Odd elements of the Arrayā€ is an elementary problem of array data structure for beginners. Here, we are given an array of size ā€˜nā€™ and our task is to count the number of even elements and number of odd elements of an array.

Example:

INPUT:
Enter the size of array: 5
Array[5] = {1, 2, 3, 4, 5}
OUTPUT:
Number of odd elements: 3
Number of even elements: 2

The steps required to count number of even and number of odd elements are as follows:

  1. Set odd_count  = 0 and even_count = 0.
  2. Start scanning the array element. For each array element, check if it even or odd.

If the array element is even number then, increment even_count by

even_count = even_count + 1.

If the array element is odd number then, increment odd_count by

odd_count = odd_count + 1.

3. Print the odd_count and even_count

C++ Program to count number of even and odd elements in an array are as follows:

/* Program to count even and odd elements in an array */  
#include<bits/stdc++.h>  
using namespace std;  
int main()  
{  
    int n;  
      
    /* Scanning size of the array */  
    cout<<"Enter the number of array elements: ";  
    cin>>n;  
      
    /* Creating an Array */  
    int arr[n];  
      
    /* Scanning the array elements */  
    cout<<"\nEnter the array elements: ";  
    for(int i = 0; i < n; i++)  
    cin>>arr[i];  
      
    int odd_count = 0;  
    int even_count = 0;  
      
    /* Count the even and odd elements */  
    for(int i = 0; i < n; i++)  
    {  
        if(arr[i] % 2 == 0)  
        even_count = even_count + 1;  
        else if(arr[i] % 2 != 0)  
        odd_count = odd_count + 1;  
    }  
      
    /* Printing the result */  
    cout<<"\nThe number of odd elements in an array are: "<<odd_count<<"\n";  
    cout<<"The number of even elements in an array are: "<<even_count<<"\n";  
}  

OUTPUT:
 
Enter the number of array elements: 5
Enter the array elements: 1 2 3 4 5
The number of odd elements in an array are: 3
The number of even elements in an array are: 2
 Time Complexity:
O(n), where n is the size of the array

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *