Home>Article>Backend Development> How to implement cumulative summation from 1 to n in C language

How to implement cumulative summation from 1 to n in C language

青灯夜游
青灯夜游 Original
2021-04-15 18:09:34 49307browse

1. For loop, the syntax is "for(i=1;i

How to implement cumulative summation from 1 to n in C language

The operating environment of this tutorial: windows7 system, c99 version, Dell G3 computer.

Problem description: Use C language to implement the accumulation of 1 2 3 4 5 ... n.

Method 1: Use a for loop. The specific code is as follows:

#include int add(int n){ int i,sum=0; for(i=1;i

The running results are as follows:

How to implement cumulative summation from 1 to n in C language

Method 2: Use a while loop. The specific code is as follows:

#include int add(int n){ int i=1,sum=0; while(i

The main() function is consistent with the function of the for loop. Of course, it can also be modified according to your own needs. The specific running results are as follows:

How to implement cumulative summation from 1 to n in C language

Method 3: Use do-while loop, the specific code is as follows:

#include int add(int n){ int i=1,sum=0; do{ sum=sum+i; i++; }while(i

The running result is as follows:

How to implement cumulative summation from 1 to n in C language

Related recommendations: "C Language Video Tutorial"

The above is the detailed content of How to implement cumulative summation from 1 to n in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn