Question: a given integer N is required to calculate the sum of all integers from 0 to n.
Solution 1: increment by using the for loop.
#include <stdio.h>int main(void){ int x; printf("Input an integer:\n"); scanf("%d", &x); printf("sum=%d\n", sum(x)); return 0;};int sum(int x){ int i, result=0; for(i=0; i<=x; i++){ result+=i; } return result;};
Solution 2: The question is actually an arithmetic difference sequence with the first entry being 0, the last entry being N, and the tolerances being 1. According to the arithmetic difference summation formula: s [N] = N * (n + 1) /2 or s [N] = (a [1] + A [n]) * n/2.
#include <stdio.h>int main(void){ int x; printf("Input an integer:\n"); scanf("%d", &x); printf("sum=%d\n", sum(x)); return 0;};int sum(int x){ return (x + 1)*x/2;};
Input and input:
$ ./a.out Input an integer:100sum=5050
Arithmetic difference sequence Formula
An = A1 + (n-1) d
Sn = Na1 + N (n-1) D/2
N indicates the length of a sequence.
A1 indicates the first item.
D indicates the tolerances.
SN indicates the sum of N items.