C++ Program to find Sum of Even Numbers

Write a C++ Program to find the sum of even numbers from 0 to n. This C++ program allows you to enter the maximum number. Next, we used the for loop (for(number = 1; number <= maximum; number++)) to iterate numbers from 1 to maximum. We used the If condition within the loop to check whether the number % 2 equals to 0. If true, add that number to the sum value (sum = sum + number;), and print the number value as the even number.

#include<iostream>
using namespace std;

int main()
{
	int number, maximum, sum = 0;
	
	cout << "\nPlease Enter the Maximum Limit for Even Numbers  =  ";
	cin >> maximum;	
	
	cout <<"\nEven Numbers between 0 and " << maximum << " = ";
	for(number = 1; number <= maximum; number++)
	{
  		if ( number % 2 == 0 ) 
		{
  			cout << number << " ";
			sum = sum + number;
		}
	}
	
	cout << "\nThe Sum of All Even Numbers upto " << maximum << " = " << sum;
	
 	return 0;
}
Please Enter the Maximum Limit for Even Numbers  =  20

Even Numbers between 0 and 20 = 2 4 6 8 10 12 14 16 18 20 
The Sum of All Even Numbers upto 20 = 110

C++ Program to find the sum of even Numbers Example 2

In this C++ program to calculate the sum of even Numbers, we altered the for loop (for(number = 2; number <= maximum; number = number + 2)) to remove the If statement. As you can see, we incremented the number to 2 (instead of 1 number++). As we know, every number starts from 2 with an increment of 2 will be an even number. So, we add that number to the sum and print the sum as a result.

#include<iostream>
using namespace std;

int main()
{
	int number, maximum, sum = 0;
	
	cout << "\nPlease Enter the Maximum Limit for Even Numbers  =  ";
	cin >> maximum;	
	
	cout <<"\nEven Numbers between 0 and " << maximum << " = ";
	for(number = 2; number <= maximum; number = number + 2)
	{		
		sum = sum + number;
		cout << number << " ";
	}
	
	cout << "\nThe Sum of All Even Numbers upto " << maximum << " = " << sum;
	
 	return 0;
}
Please Enter the Maximum Limit for Even Numbers  =  30

Even Numbers between 0 and 30 = 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 
The Sum of All Even Numbers upto 30 = 240

This C++ sum of even numbers example allows the user to enter the minimum and maximum value. Next, it will calculate the sum of even numbers from minimum to maximum.

#include<iostream>
using namespace std;

int main()
{
	int number, minimum, maximum, sum = 0;
	
	cout << "\nPlease Enter the Minimum Limit for Even Numbers  =  ";
	cin >> minimum;	
	
	cout << "\nPlease Enter the Maximum Limit for Even Numbers  =  ";
	cin >> maximum;	
	
	cout <<"\n\nEven Numbers between  " << minimum << " and " << maximum << " = ";
	for(number = minimum; number <= maximum; number++)
	{		
		if ( number % 2 == 0 ) 
		{
  			cout << number << " ";
			sum = sum + number;
		}
	}
	
	cout << "\nThe Sum of All Even Numbers from " << minimum << " to " << maximum << " = " << sum;
	
 	return 0;
}
C++ Program to find Sum of Even Numbers