How about designing the loop, but not at the 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 this sum S
.
What happens if we take this list and add it back?
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 is worth S
. Since it is a finite sum, reversing the elements will not change the final result, so the reverse list is also worth 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
Because n
is an integer, n*(n+1)
is necessarily an even number. Therefore, dividing by 2 will result in an integer. To ensure the value, it costs nothing to force the multiplication precedence prior to splitting:
( n*(n+1) )/2
So, if you want to know the value for the sum up to 64, you 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;
}