+ 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); }

21st Jul 2023, 9:18 AM
Abdullah Al Zunaid
3 Answers
+ 4
"i" is never changed. Write i+=2 instead of i+2
21st Jul 2023, 9:35 AM
Lisa
Lisa - avatar
+ 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
22nd Jul 2023, 6:50 AM
MohammadRezaKamyab
MohammadRezaKamyab - avatar
+ 2
i+=2 or (i=i+2) instead i+2 Good luck you can also write sum=sum+i or sum+=i
21st Jul 2023, 6:21 PM
Mar Change
Mar Change - avatar