Tính tổng S(n) = 1+2+3+4+ … +n

Yêu cầu:
– Nhập vào số nguyên dương n
– Tính tổng s(n) = 1 + 2 + 3 + 4 + … + n

Giải thuật:
– Dùng vòng lặp for, do while để duyệt biến i từ 1 tới n
– Tính tổng: s = s + i

Code

/************************************************************
* Author: VNCODING
* History
* 2016/12/12        first create    VNCODING
*************************************************************/

#include <stdio.h>
#include <conio.h>

int main()
{
	printf("S(n) = 1+2+3+4+ … +n\n");
	int i, n, s = 0;
	do
	{
		printf("n = ");
		scanf("%d", &n);
	}while(n <= 0);
	
	for(i = 1; i <= n; i++)
	{
		s += i;
	}
	printf("\nS(%d) = %d", n, s);
	getch();
	return 0;
}

Kết quả:

Tính tổng S(n) = 1+2+3+4+ … +n
Tính tổng S(n) = 1+2+3+4+ … +n

1 Comment on Tính tổng S(n) = 1+2+3+4+ … +n

Leave a Reply to mum Cancel reply