Q3. Count number of even numbers in an array

Program to count the number of even numbers in an integer array

Notice how you need to use size of array separately as there is no array.length in C++ like in Java
Also notice how to pass an array to a function

/* countevens.cpp */
 
#include <iostream>
using namespace std;
 
int countevens(int array[], int arrsize);
 
int main() {
    int array[] = {1,2,3,4,5,6,7};
 
    //call the countevens() function
    int evencount = countevens(array, 6);
    cout << "Even count in array is:" << evencount << endl;
 
    cin.get(); //small trick the stop the output window from going away    
} 
 
int countevens(int arr[], int arrsize) {
    int evencount = 0;
 
    for (int i = 0; i < arrsize; i++)
        if (arr[i] % 2 == 0)
           evencount++;
 
    return evencount;
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License