Home>Article>Backend Development> 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:
#includeint add(int n){ int i,sum=0; for(i=1;i The running results are as follows:
Method 2: Use a while loop. The specific code is as follows:
#includeint 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:
Method 3: Use do-while loop, the specific code is as follows:
#includeint add(int n){ int i=1,sum=0; do{ sum=sum+i; i++; }while(i The running result is as follows:
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!