for loop

Would someone kindly show me the code of using a for loop to obtain and display the sum of odd integer in the range of 11 to 121 ?

thanks !
Just a hint: odd integers meet this condition: x % 2 == 1
1
2
3
4
5
6
7
8
9
10
int sum=0;

for(int i=11; i<=121; i++)
{
     if(i%2 == 1)
      {
          sum = sum + i;
       }
}
cout<<sum<<endl;



Hope this will help you
It would be more efficient to increment i by 2 each time:

1
2
3
4
5
6
7
int sum=0;

for(int i=11; i<=121; (i + 2))
{
          sum = sum + i;
}
cout<<sum<<endl;


This way you're only iterating over half the values, and saving a check each time.

(Note: You can probably use a variation of Euler's counting formula to solve this without using a for loop)
Oops I made a mistake. The update condition in the for loop above should read (i = i+2).
Actually the formula for the sum of the first N odd numbers (1, 3, 5, ...(2N-1)) is simply N^2. All you have to do then is take into account the offset. It works out that the sum of N odd numbers starting at odd number x is N(N + x - 1).

So, from 11 to 121 inclusive, there are 56 odd values if I'm not mistaken. You're starting at 11, so you could just write:

 
cout << 56*(56 + 11 - 1)


Which gives 3696, which I believe is correct. But I guess the point of the exercise was to learn about for loops, not counting sequences hehe :).
Topic archived. No new replies allowed.