0
Add all odd numbers in a given range?
In c++, can somebody help me make a program that sums all odd numbers in a range? Somebody needed this in a Discord server i'm in, his range was 7 to 37. I can't figure out how to add the numbers. I thought that maybe I could add all the values to an array, but it didn't work. Just printed 0 16 times. I also don't know how to sum the elements of an array in c++.
1 Réponse
+ 6
It's maybe not the answer you're looking for because theres little code involved but it's actually easy with some maths:
The fist n odd numbers summed up is equal to n*n.
So, say, you want the sum of all the odds from 1 to 17. 17 is the ((17+1)/2)-th odd number (every other number is odd so you just divide by 2).
So the sum of all odds from 1 to 17 is ((17+1)/2)^2.
or generally
f(x)=((x+1)/2)^2
To get the sum of all odd numbers in a range from `a` to `b` (not starting at 1), you simply do f(b)-f(a).
Anyway a simpler solution is
sum = 0
for(i = start; i <= end; i += 2)
sum += i;
but it's not as nice :)