Count number of even and odd elements in an array in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to find the number of even and odd elements in an array.

For this we will be provided with an array. Our task is to calculate the number of even and odd elements in the given array.

Example

 Live Demo

#include<iostream>
using namespace std;
void CountingEvenOdd(int arr[], int arr_size){
   int even_count = 0;
   int odd_count = 0;
   //looping through the elements
   for(int i = 0 ; i < arr_size ; i++) {
      //checking if the number is odd
      if (arr[i]%2 != 0)
         odd_count ++ ;
      else
         even_count ++ ;
   }
   cout << "Number of even elements = " << even_count
      << "\nNumber of odd elements = " << odd_count ;
}
int main(){
   int arr[] = {2, 3, 4, 5, 6};
   int n = sizeof(arr) / sizeof(arr[0]);
   CountingEvenOdd(arr, n);
}

Output

Number of even elements = 3
Number of odd elements = 2
raja
Published on 05-Feb-2020 12:22:21
Advertisements