Hi all. I'm having a problem with my output displaying the correct integer. User is prompted to enter 2 integers. Part of the code determines evens and odds and sum of even.
After the coding of the Even and Sum requirements, I output the sum of the evens, but when coding the cout of the firstNum and secondNum (entered by user), the firstNum is displaying the wrong number, which I believe is because of the previous coding counter.
Below is code; then following is the text in the console output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int firstNum, secondNum;
int evens, odds;
int sum = 0;
cout << "Enter 2 integers. The second must be larger \n"
<< "than the first number.";
cin >> firstNum >> secondNum;
cout << endl;
if (firstNum >= secondNum)
{
cout << "Your first number is not smaller than the second. \n"
<< "Please reenter the two numbers.";
cin >> firstNum >> secondNum;
cout << endl;
}
else
while(firstNum <= secondNum)
{
if(firstNum % 2 != 0)
cout << firstNum << " is odd." << endl;
else
sum += firstNum;
firstNum++;
}
cout << "The sum of all even numbers between " << firstNum << " and " << secondNum << " is " << sum << "."
<< endl;
return 0;
}
|
[OUTPUT]
Enter 2 integers. The second must be larger
than the first number. 1 13
1 is odd.
3 is odd.
5 is odd.
7 is odd.
9 is odd.
11 is odd.
13 is odd.
The sum of all even numbers between
14 and 13 is 42.
Press any key to continue . . .
The BOLD and UNDERLINED number is supposed to be 1 not 14. And the Sum is NOT supposed to be 42, but instead the Sum of all even numbers.
Ideas of how to reverse this?