In this blog, we will create a program to find the sum of even numbers from an array in the C++ programming language.
Algorithm to create the respective code
Here we can use a modular operator to find even numbers in an array
if n%2==0, n is an even number – if the number is even, the remainder is zero.
C++ program to find the sum of even numbers from an array
#include <iostream> #include <conio.h> using namespace std; int main() { int evenSum=0; int i,size; cout<<"Enter the size of the array: "; cin>>size; int arr[size]; cout<<"Enter the Array elements: "; for(i=0; i<size; i++) { cin>>arr[i]; } for(i=0; i<size; i++) { if(arr[i]%2==0) evenSum=evenSum+arr[i]; } cout<<"\nThe sum of even numbers are:"<<evenSum; getch(); return 0; }
Output of the above code
Explanation of the above code
- To begin with, it declares and initializes two variables: evenSum=0, and size.
- It also receives input from the user regarding the length of the array.
- It then defines an array without including elements.
- Then the elements for the array are received from the user.
- Then, a “for loop” is used to add the elements one by one to the array.
- Then, a second “for” loop is used to select elements one by one from the array to determine which numbers are even.
- Next, “if” statements are used to find the number, and if it is even, it is added to the even sum. If the number is not even, it is neglected.
- Finally, the sum of even numbers is displayed.