I was assigned to write a program that could sum all even numbers between two numbers that a user inputted (assuming the first number was less than the second number). We have to use a for loop for this problem, and I cannot get the correct output/sum. Here is my code, please feel free to comment any solutions. When I input 4 and 36 as my two ints, the sum should be 340, but I keep getting 320.
#include <iostream>
usingnamespace std;
int main() {
int firstNum;
int secondNum;
int loopNum;
int sum;
sum = 0;
if (firstNum % 2 == 0)
{
firstNum = firstNum + 1;
}
for (loopNum = firstNum; loopNum <= secondNum; loopNum +=2)
{
if (loopNum % 2 != 0)
{
sum += loopNum;
}
}
cout << endl <<"The sum of the even numbers is ==> " << sum << endl;
return 0;
}
#include <iostream>
int main()
{
std::cout << "Enter your first number: ";
int firstNum { };
std::cin >> firstNum;
std::cout << "Enter your second number: ";
int secondNum { };
std::cin >> secondNum;
std::cout << '\n';
int sum { };
for (int loopNum { firstNum }; loopNum <= secondNum; loopNum++)
{
if (loopNum % 2 == 0)
{
sum += loopNum;
}
}
std::cout << "The sum of the even numbers is: " << sum << '\n';
}
Enter your first number: 1
Enter your second number: 11
The sum of the even numbers is: 30
It's more efficient to make the firstNum even and add by twos like the original program attempted to do. Here is a modified version of Furry Guy's program that does that by fixing the original bug:
#include <iostream>
int main()
{
std::cout << "Enter your first number: ";
int firstNum { };
std::cin >> firstNum;
if (firstNum % 2 == 1) { // if firstNum is odd
++firstNum; // add one to make it even
}
std::cout << "Enter your second number: ";
int secondNum { };
std::cin >> secondNum;
std::cout << '\n';
int sum { };
for (int loopNum { firstNum }; loopNum <= secondNum; loopNum += 2)
{
sum += loopNum;
}
std::cout << "The sum of the even numbers is: " << sum << '\n';
}
The purpose of the assignment is to use loops, but if you were solving this problem in the real world, you'd use the formula for an arithmetic series:
1 2 3 4 5 6 7
if (secondNum % 2 == 1) {
--secondNum; // make secondNum even
}
int numTerms = (secondNum-firstNum) / 2 + 1;
std::cout << "Doing it the easy way, the sum is "
<< (firstNum+secondNum)/2 * numTerms << std::endl;
#include <iostream>
usingnamespace std;
int main()
{
int a, b;
cout << "Input a, b (with 0 <= a <= b): "; cin >> a >> b;
a++; a /= 2; b /= 2;
cout << "The sum of the even numbers is " << b * b - a * a + a + b << '\n';
}
#include <iostream>
usingnamespace std;
int main() {
int x, y, sum = 0;
cout<<"Enter first number: ";
cin>>x;
cout<<"Enter second number: ";
cin>>y;
x = x + x%2;
for (int i = x; i <= y; i +=2)
{
sum = sum + i;
}
cout <<"The sum of all even numbers between "<<x<<" and "<<y<<" is "<<sum;
return 0;
}