Write a program in C language to calculate the value accumulated from 1 to n, s=1+2+3+……+n

Accumulation and summation is a classic case of loop. How to implement it?

Of course it's a cycle

Loops include while statements, do-while statements, and for statements. Let’s try all three statements.

1.While statement implementation

#include<stdio.h>
int main()
{
	int i=1,n,sum=0;
	printf("n:");
	scanf("%d",&n);
	while(i<=n)
	{
		sum+=i;
		i++;		
	}
	printf("sum=%d",sum);
	return 0;
}

2.for statement implementation

#include<stdio.h>
int main()
{
	int i=1,n,sum=0;
	printf("n:");
	scanf("%d",&n);
	for(;i<=n;i++)
	{
		sum+=i;		
	}
	printf("sum=%d",sum);
	return 0;
}

Try it yourself using do-while statement

Guess you like

Origin blog.csdn.net/studyup05/article/details/130331432
Recommended