### How to find squares of odd numbers in an interval

How would I write a for loop that finds the square of all odd numbers in an interval? I figured out all the other steps, but this is the last thing that I need to figure out
Here is how you would iterate through the interval [a, b]:
 ``1234`` ``````for (int i = a; i <= b; i++) { // ... }``````

To check if a number is odd:
 ``1234`` ``````if (number % 2 != 0) { // number is odd }``````

To square a number:
 `` `` ``int number_squared = number * number;``

Can you now combine these concepts?

Edit: Did you mean the sum of the square of all odd numbers? If so, the same concept applies, but you need to keep track of a sum variable and add to it each iteration.

 ``123456`` ``````int sum = 0; for ( /* ... */ ) { // ... sum += number_squared; }``````
Last edited on
 ``12345678910111213`` ``````#include using namespace std; void odds( int a, int b ) { for ( int i = a + 1 - a%2; i <= b; i += 2 ) cout << i * i << " "; cout << '\n'; } int main() { odds( -18, 19 ); }``````

If, as @Ganado surmises, you actually want the sum of the squares of the odd numbers, then you can either put a summation within that loop or you could, in principle, do it analytically (making sure that you don't overflow):
 ``123456789101112131415161718`` ``````#include using namespace std; int sumOddSquared( int a, int b ) { if ( a > b ) return sumOddSquared( b, a ); if ( a % 2 == 0 ) a++; if ( b % 2 == 0 ) b--; if ( a > b ) return 0; int bp = b + 1, am = a - 1; return ( bp * bp * bp - am * am * am - bp + am ) / 6; } int main() { cout << sumOddSquared( -18, 19 ) << '\n'; }``````
Last edited on