Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C++ Exercises: Count even number of elements in a given array of integers

C++ Basic Algorithm: Exercise-98 with Solution

Write a C++ program to count even number of elements in a given array of integers.

Sample Solution:

C++ Code :

#include <iostream>
using namespace std;

static int test(int nums[], int arr_length)
          {
            int evens = 0;

            for (int i = 0; i < arr_length; i++)
            {
                if (nums[i] % 2 == 0) evens++;
            }
            return evens;
          }    
               
int main() 
 {  
  int nums1[] = {1, 5, 7, 9, 10, 12};
  int arr_length = sizeof(nums1) / sizeof(nums1[0]);	
  cout << test(nums1, arr_length) << endl; 
  int nums2[] = {0, 2, 4, 6, 8, 10};
  arr_length = sizeof(nums2) / sizeof(nums2[0]);	
  cout << test(nums2, arr_length) << endl;  
  return 0;    
}

Sample Output:

2
6

Pictorial Presentation:

C++ Basic Algorithm Exercises: Count even number of elements in a given array of integers.

Flowchart:

Flowchart: Count even number of elements in a given array of integers.

C++ Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C++ program to find the largest value from first, last, and middle elements of a given array of integers of odd length (atleast 1).
Next: Write a C++ program to compute the difference between the largest and smallest values in a given array of integers and length one or more.

What is the difficulty level of this exercise?