+ 1
How should be the code to get sum of even numbers from series entered by user in c language
Sum of even numbers https://code.sololearn.com/cCs7bayljEzo/?ref=app
5 Respuestas
+ 4
When you say "series", did you mean values in range, or what? I see your code only reads variable <n>, so I'm a bit confused.
Describe the task in brief ...
(Edit)
If you want to sum even numbers until <n>, assuming only positive numbers, you can do something like this ...
int x = 2;
while( x <= n )
{
sum += x;
x += 2;
}
+ 3
Let me see your code? can't say anything without looking at the code ...
https://www.sololearn.com/post/75089/?ref=app
+ 2
I uploaded code
https://code.sololearn.com/cCs7bayljEzo/?ref=app
+ 2
Variable 'x' is unnecessary, as you assigned it to the same value as n, why don't you just use n instead?
About while loop. It executes only ones, or twice depends on input.
while(x%2==0) {...} and then
while((x+1)%2==0) {...}
One of these must return False and break the loop
If you want to sum all even values from 0 to x i would recommend you using for loop instead, cuz you can predict number of iterations. As we know that you are going to use only even numbers, we can write the loop:
for(int i = 0; i<=x; i+=2){
sum+=i;
}