+ 2
I think my logic here is ok but it's going into infinite loop why?
I completed this code with if statement in for loop but thought it can be done with just for loop but its running infinitely I cant find what have gone wrong. Please can some one help fine the problem. Thanks. #include <stdio.h> int main(void) { //sum of odd numbers in first n int int n; int sum = 0; scanf("%d", &n); for(int i = 1; i <= n; i+2) { printf("%d ",i); sum = sum + i; } printf("\nthe sum is: %d", sum); }
3 Réponses
+ 4
"i" is never changed. Write i+=2 instead of i+2
+ 3
Apart from your logic there's another efficient way to this solution in constant time 👌
Sum of odd numbers = total sum - sum of even numbers
Total sum = n × (n +1) / 2
Now let's take a look at sum of even number
2 + 4 + 6 + ... + n
We factor 2 in this equation
2 (1 + 2 + ...+ n/2)
So the sum of even numbers would be
2 × (n/2 × (n/2 +1) / 2) =
n/2 × (n/2 + 1)
Now you can find the sum of odd numbers
Total - sum_even = sum_odd
+ 2
i+=2 or (i=i+2) instead i+2
Good luck
you can also write sum=sum+i
or sum+=i