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]:
1
2
3
4
for (int i = a; i <= b; i++)
{
    // ...
}


To check if a number is odd:
1
2
3
4
if (number % 2 != 0)
{
    // number is odd
}


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

Can you now combine these concepts?

See also, the site's tutorial on control flow: http://www.cplusplus.com/doc/tutorial/control/

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.

1
2
3
4
5
6
int sum = 0;
for ( /* ... */ )
{
    // ...
    sum += number_squared;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
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):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
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
Topic archived. No new replies allowed.