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
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;
}
#include <iostream>
usingnamespace 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>
usingnamespace 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';
}