How about including at design level the loop, but not at code level?
Well, your question is clearly mathematical. As such, it could be solved mathematically.
You have the numbers 1, 2, 3..., n
, for a n
any. Be the value of that sum S
.
What happens if we take this list and add it to the reverse of it?
1 + 2 + 3 + ... + (n-1) + n
n + (n-1) + (n-2) + ... + 2 + 1
-------------------------------------------
(n+1) + (n+1) + (n+1) + ... + (n+1) + (n+1)
The first list goes S
. Since it is a finite sum, reversing the elements will not alter the final result, so the reverse list is also valid S
. This means that the sum of the two lists is 2S
. Note that the term (n+1)
is repeated n
times, therefore:
2S = n*(n+1)
Hence:
S = n*(n+1)/2
Like n
is a whole, n*(n+1)
necessarily is an even number. Therefore dividing by 2 will result in an integer. To guarantee the value, it costs nothing to force the multiplication precedence before the division:
( n*(n+1) )/2
So, as one wishes to know the value for the sum up to 64, could do (64*65)/2
or leave it in the variable, which would be easier to change to another value in the future:
#include <stdio.h>
int main()
{
int n = 64;
printf("%d\n", ( n*(n+1) )/2);
return 0;
}
This is what you need
soma += numero;
(inside the loop)?– gato
@cat would be yes. See Maniero’s answer
– Jefferson Quesado
vlw by the help manow
– nazinho pb
@nazinhopb Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already done so. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero