Check all the elements in an array are even using library in C++

We are given an array of elements and we have to check the whether each element is even or not.

Examples:

Input : [2, 4, 6, 8, 9]
Output : All the elements are not even

Input : [4, 6, 8, 12, 14]
Output : Alla the elements are even

Approach: The above problem can be solved using for loop but in C++ we have all_of() algorithm which operates on whole array and save time to write code for loop and checks each element for the specified property.

Note that all_of() also uses loop internally, it just saves our time of writing a loop code.

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to check if all elements
// of an array are even or odd.
#include <algorithm>
#include <iostream>
using namespace std;
  
void even_or_not(int arr[], int len)
{
    // all_of() returns true if given operation is true
    // for all elements, otherwise returns false.
    all_of(arr, arr + len, [](int i) { return i % 2; }) ? 
                        cout << "All are even elements"
                        cout << "All are not even elements";
}
  
int main()
{
    int arr[] = { 2, 4, 6, 12, 14, 17 };
    int len = sizeof(arr) / sizeof(arr[0]);
    even_or_not(arr, len);
    return 0;
}

chevron_right


Output:

All are not even elements


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.