How do I Output only One Number Instead of Multiple in a Loop

I am writing a program that does multiple things. For the last part I need to output the sum of the squares of all the odd numbers between two numbers that the user inputs earlier in the program.

1
2
3
4
5
6
7
8
9
  		//sum of squared odd numbers between firstNum and secondNum
		for (number = firstNum; number <= secondNum; number++)
		{
			if (number % 2 != 0)
			{
				sum = sum += pow(number, 2);
				cout << "\nThe sum of the squares of all odd numbers between " << firstNum << " and " << secondNum << " is: " << sum << endl;
			}
		}


Everything works, I get the correct answer at the end and everything, however the output lists each step individually rather than one whole number i.e:

"The sum of the squares of all odd numbers between 2 and 14 is: 9"

"The sum of the squares of all odd numbers between 2 and 14 is: 34"

"The sum of the squares pf all odd numbers between 2 and 14 is: 83" etc. etc.

Where what is happening is it first shows 3^2, then it shows 3^2+5^2, then 3^2+5^2+7^2, all the way up until the end of the loop. I still get the correct answer however i just want it to show the final answer not all of the steps leading up to it.

Thank you,
ZSquared
If you want it to only print out the final answer, and not each step, couldn't you simply move it outside of the loop?

1
2
3
4
5
6
7
8
9
10
//sum of squared odd numbers between firstNum and secondNum
		for (number = firstNum; number <= secondNum; number++)
		{
			if (number % 2 != 0)
			{
				sum = sum += pow(number, 2);
				
			}
		}
             cout << "\nThe sum of the squares of all odd numbers between " << firstNum << " and " << secondNum << " is: " << sum << endl;
That did the trick! I had actually thought of that, but I must have only put it outside of the if statement rather than the entire for loop. Thanks for the help even though it was something so simple!
My pleasure, Goodluck^^
Topic archived. No new replies allowed.