The sum of even integers from 1 to 100

Solved
MEdAmine0101 Posted messages 110 Status Member -  
KX Posted messages 19031 Status Moderator -
Hello,

Write a program that calculates among the integers from 1 to 100:

1. The sum of even integers.
2. The sum of the squares of the odd integers.
3. The sum of the cubes of these integers

First, I tried to write:

for(i=1;i<=100;i++)
{
if(i!%2)
/*even integers ...*/
else
/*odd integers..*/

But to calculate the sum I don't even know what to do...
So I wish you could help me solve the exercise because we haven't already covered this kind of exercises, the sum of a sequence or series if you have links that can help me feel free to suggest them.....
And thank you in advance!

Configuration: Windows XP / Firefox 4.0

3 answers

  1. nicocorico Posted messages 846 Status Member 138
     
    Well, you can continue along those lines by adding a global variable for each calculation, which you initialize to 0 and into which you add i in each loop,
    then i squared, etc...
    3
    1. MEdAmine0101 Posted messages 110 Status Member
       
      Alors j'ai besoin de somme1, somme2, somme3 ;
      mais la formule que je dois y appliquer !!!!??!!!!
      somme1 = (i*1) + (i*2) + (i*3).........(100)
      somme2 = (i*(2n+1))²......
      0
    2. JooS Posted messages 2705 Status Member 228
       
      Hello!!!
      Your method is correct, but you can remove the tests and reduce the number of iterations like this!!! Hoping it's right :)

      somme1 = 0; somme2 = 0; somme3 = 0; for(i=0; i<100;i+=2) { somme1 += i; // We add the even number(i) at each iteration somme2 += (i+1)*(i+1); // We add the odd number(i+1) which is multiplied by itself(square) somme3 += ((i)*(i)*(i))+((i+1)*(i+1)*(i+1)); // We add the triple(cube) of the even number(i) added to the triple of the next odd number(i+1) at each iteration }
      0
    3. MEdAmine0101 Posted messages 110 Status Member
       
      i+=2 means "increment i by 2".
      Similarly, += i means "add the value of i to the variable on the left".
      According to your method, you could add an if-else statement to handle even and odd integers.
      0
    4. KX Posted messages 19031 Status Moderator 3 020
       
      a += b; is equivalent to a = a + b;
      Here i+=2 allows you to go directly from one even number to the next, so i is always even, and i+1 is always odd, so there is no need to test if i is even or odd, we already know!

      For the basics of C, see C Language, especially The operators and The conditional structures.
      0