The sum of even integers from 1 to 100
Solved
MEdAmine0101
Posted messages
110
Status
Member
-
KX Posted messages 19031 Status Moderator -
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
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
-
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...-
-
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 } -
-
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.
-