Home >Backend Development >C#.Net Tutorial >How to implement cumulative summation from 1 to n in C language
1. For loop, the syntax is "for(i=1;i
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<stdio.h> int add(int n){ int i,sum=0; for(i=1;i<p>The running results are as follows: </p> <p><img src="https://img.php.cn/upload/article/000/000/024/3baeba1bd04a154dcb498bea9e9af935-0.png" alt="How to implement cumulative summation from 1 to n in C language"></p> <p><strong>Method 2: Use a while loop. The specific code is as follows: </strong><br></p> <pre class="brush:php;toolbar:false">#include<stdio.h> int add(int n){ int i=1,sum=0; while(i<p>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: </p> <p><img src="https://img.php.cn/upload/article/000/000/024/3baeba1bd04a154dcb498bea9e9af935-1.png" alt="How to implement cumulative summation from 1 to n in C language"></p> <p><strong>Method 3: Use do-while loop, the specific code is as follows: </strong></p> <pre class="brush:php;toolbar:false">#include<stdio.h> int add(int n){ int i=1,sum=0; do{ sum=sum+i; i++; }while(i<p>The running result is as follows: </p> <p><img src="https://img.php.cn/upload/article/000/000/024/956db51426d2e9fa74ef14c50ccc3a16-2.png" alt="How to implement cumulative summation from 1 to n in C language"></p> <p>Related recommendations: "<a href="http://www.php.cn/course/list/37.html" target="_blank">C Language Video Tutorial</a>"<br></p></stdio.h>
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!