How to perform cumulative addition in C language?

In the C language, you can use loop statements and an accumulator variable to perform an accumulation operation. The specific steps are as follows:

  1. Declare an accumulator variable and initialize it to 0.
  2. Use loop statements (such as for loop or while loop) to iterate through a sequence of numbers that need to be accumulated.
  3. Within the loop, add each numerical value to the accumulating variable.
  4. After the loop ends, the value in the accumulator variable is the cumulative result.

Here is an example code:

#include <stdio.h>

int main() {
    int n;  // 需要累加的数值
    int sum = 0;  // 累加变量

    printf("请输入一个整数:");
    scanf("%d", &n);

    // 使用循环累加
    for (int i = 1; i <= n; i++) {
        sum += i;
    }

    printf("1到%d的累加结果为:%d\n", n, sum);

    return 0;
}

Running this code, the user will input an integer n, and the program will calculate the sum of numbers from 1 to n, and display the result on the screen.

bannerAds