Hi there,
Currently, I am working on an assignment that involves multiple loops, each computing a simple mathematical statement. I am stuck on Part d, "Output the sum of the square of odd numbers between firstNum and secondNum. Use a loop of your choice." Part d is labeled in my code as //Begin Part d. The output I receive seems to only square the last odd number in the sequence and does not sum the previous squares. I have tried other loop types with no success. Here it is, please go easy on the newb! :D
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
usingnamespace std;
int main()
{
int number1 = 1, number2 = 65, firstNum, secondNum, oddNum, evenNum, setNum, resultB = 0, resultC = 0, oddSquare = 0, square1;
char letter;
cout <<setiosflags(ios::fixed | ios::showpoint);
cout <<setprecision(2);
cout << "Welcome to the Number Functions Program\n";
cout << endl;
cout << endl;
cout << "Please input two whole numbers and press Enter\n";
cout << "(Note: The first number must be less than the second number)\n";
cin >> firstNum >> secondNum;
cout << endl;
setNum = firstNum % 2;
if (setNum == 0)
{
oddNum = firstNum + 1;
evenNum = firstNum;
}
else
{
oddNum = firstNum;
evenNum = firstNum + 1;
}
cout << "Part a - Odd integers between " << firstNum << " and " << secondNum << " are: ";
while (oddNum < secondNum)
{
cout << oddNum << " ";
oddNum = oddNum + 2;
}
cout << endl;
cout << endl;
cout << "Part b - Sum of even integers between " << firstNum << " and " << secondNum << " = ";
do
{
resultB = resultB + evenNum;
evenNum = evenNum +2;
}
while (evenNum <= secondNum);
cout << resultB;
cout << endl;
cout << endl;
cout << "Part c:\n";
cout << endl;
cout << "Number Square\n";
for (int number1 = 1; number1 <= 10; number1++)
{
square1 = number1 * number1;
cout << " " << number1 << " " << square1 << endl;
}
cout << endl;
cout << "Part d - Sum of the squares of odd integers between " << firstNum << " and " << secondNum << " = ";
cout<< "\n";
cout<< "Oddnumber before entering while loop" << " " << oddNum << endl;
cout<< "secondNumber before entering while loop" << " " << secondNum << endl;
while (oddNum <= secondNum)
{
oddSquare = oddNum * oddNum;
resultC = resultC + oddSquare;
oddNum = oddNum + 2;
}
cout << resultC;
cout << endl;
cout << endl;
return 0;
}
Your setting the oddNumber value in your first while loop that way your just skipping your second while loop. I just added two more cout's to the code, just before entering the second while loop so that you can see the values.
HTH