Tutorials
Examples
Tests

# C++ Program to Find Sum of Even and Odd Numbers

This article provides some programs in C++ that find and prints the sum of all even and odd numbers from the list of some random numbers entered by user. The program is created in following two ways:

• Using for loop
• Using while loop

## Find Sum of Even and Odd Numbers using for Loop

The question is, write a C++ program that receives 10 numbers from user and prints the sum of all even and all odd numbers. The program given below is its answer:

#include<iostream>

using namespace std;
int main()
{
int arr[10], i, eve=0, odd=0;
cout<<"Enter any 10 numbers: ";
for(i=0; i<10; i++)
cin>>arr[i];
for(i=0; i<10; i++)
{
if(arr[i]%2==0)
eve = eve+arr[i];
else
odd = odd+arr[i];
}
cout<<"\nSum of Even Numbers = "<<eve;
cout<<"\nSum of Odd Numbers = "<<odd;
cout<<endl;
return 0;
}

This snapshot shows the initial output produced by above C++ program on finding the sum of even and odd numbers from a given array:

Now supply the input say 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 as ten numbers for the array and then press ENTER key to find and print sum of even and odd numbers from all these given 10 numbers like shown in the snapshot given below:

#### Modified Version of Previous Program

This is the modified version of previous program, allows user to define the size of array too along with its elements or numbers. Also this program included some message to print when no even or odd number found in the given list of numbers.

#include<iostream>

using namespace std;
int main()
{
int n, i, eve=0, odd=0;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
cout<<"Enter any "<<n<<" numbers: ";
for(i=0; i<n; i++)
{
cin>>arr[i];
if(arr[i]%2==0)
eve += arr[i];
else
odd += arr[i];
}
if(eve==0)
else
cout<<"\nSum of Even Numbers = "<<eve;
if(odd==0)
else
cout<<"\nSum of Odd Numbers = "<<odd;
cout<<endl;
return 0;
}

Here is its sample run with user input 4 as size and 1, 3, 5, 7 as four numbers:

In above program, the statement:

eve += arr[i];

is same as

eve = eve + arr[i];

## Find Sum of Even and Odd Numbers using while Loop

This is the last program of this article, created using while loop. Since while loop does not contains the initialization and update statement. Therefore we need to do initialization before the loop, and update statement in the body of the loop as shown in the program given here:

#include<iostream>

using namespace std;
int main()
{
int n, i=0, eve=0, odd=0;
cout<<"Enter the size of array: ";
cin>>n;
int arr[n];
cout<<"Enter any "<<n<<" numbers: ";
while(i<n)
{
cin>>arr[i];
if(arr[i]%2==0)
eve += arr[i];
else
odd += arr[i];
i++;
}
if(eve==0)
else
cout<<"\nSum of Even Numbers = "<<eve;
if(odd==0)