Home > Backend Development > C#.Net Tutorial > How to implement cumulative summation from 1 to n in C language

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

青灯夜游
Release: 2023-01-05 16:09:00
Original
49458 people have browsed it

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<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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template