[ create a new paste ] login | about

Link: http://codepad.org/s5LaEYCx    [ raw code | output | fork ]

C, pasted on Apr 26:
#include<stdio.h>
#include<conio.h>
int main()
{
	int n;
	// Nhập n là số dương
	do
	{
		printf("\nNhap so nguyen duong n (n >= 1): ");
		scanf_s("%d", &n);

		if (n < 1)
		{
			printf("\nGia tri n khong hop le! Vui long nhap lai");
		}

	} while (n < 1);
	/*
	Quá trình làm
	Bước 1: Xác định kiểu dữ liệu của biến cần lưu trữ
	Bước 1.1: 
	      + Nếu tính tổng thì biến lưu trữ khởi tạo là 0
		  + Nếu tính tích thì biến lưu trữ khởi tạo là 1
    Bước 2: Xác định các thành phần: Khởi tạo, điều kiện, bước lặp
	Bước 3: Xác định công thức
	*/


	/* Câu a */
	int Sa = 0;   // Bước 1
	for (int i = 1; i <= n; i++)   // Bước 2
	{
		Sa += i;             // Bước 3
	}
	printf("Sa = %d\n", Sa);

	/*
	Vd: Nhập n = 3
	Đầu tiên Sa = 0
	i = 1 => Sa = Sa + i => Sa = 0 + 1 = 1
	i = 2 => Sa = Sa + i => Sa = 1 + 2 = 3
	i = 3 => Sa = Sa + i => Sa = 3 + 3 = 6
	*/

	/* Câu b */
	int Sb = 0;
	for (int i = 1; i <= n; i++)
	{
		Sb += i * i;
	}
	printf("Sb = %d\n", Sb);

	/* Câu c */
	float Sc = 0;
	// for(int i = n; i >= 0 ; --i) chạy nhanh hơn
	for (int i = 1; i <= n; i++)
	{
		Sc += 1.0 / i;
	}
	printf("Sc = %f\n", Sc);

	/* Câu d */
	int Sd = 1;
	for (int i = 1; i <= n; i++)
	{
		Sd *= i;
	}
	printf("Sd = %d\n", Sd);

	/* Câu e 
	1! + 2! + 3! +....+ n!
	<=> 1 + 1*2 + 1*2*3 + ... + 1*2*3*...*n
	*/
	// Cách cùi bắp
	/*int Se = 0;
	for (int i = 1; i <= n; i++)
	{
		int Tich = 1;
		for (int j = 1; j <= i; j++)
		{
			Tich *= j;
		}
		Se += Tich;
	}
	printf("Se = %d", Se);*/

	// Cách víp
	int Se = 0;
	int Tich = 1;
	for (int i = 1; i <= n; i++)
	{
		Tich *= i;
		Se += Tich;
	}
	printf("Se = %d\n", Se);

	/*
	Vd n = 3
	i = 1 
	    Tich = Tich * i => Tich = 1
	    Se = Se + Tich = 0 + 1 = 1
	i = 2
		Tich = Tich * i => Tich = 2
		Se = Se + Tich = 1 + 2 = 3
	i = 3
		Tich = Tich * i => Tich = 6
		Se = Se + Tich = 3 + 6 = 9
	i = 4
		Tich = Tich * i => Tich = 24
		Se = Se + Tich = 24 + 9 = 33
	*/



	// Có thể gom lại cả 5 câu chạy 1 vòng lặp for duy nhất

	_getch();
	return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Line 17: error: conio.h: No such file or directory
In function 'main':
Line 31: error: 'for' loop initial declaration used outside C99 mode
Line 47: error: redefinition of 'i'
Line 31: error: previous definition of 'i' was here
Line 47: error: 'for' loop initial declaration used outside C99 mode
Line 56: error: redefinition of 'i'
Line 47: error: previous definition of 'i' was here
Line 56: error: 'for' loop initial declaration used outside C99 mode
Line 64: error: redefinition of 'i'
Line 56: error: previous definition of 'i' was here
Line 64: error: 'for' loop initial declaration used outside C99 mode
Line 90: error: redefinition of 'i'
Line 64: error: previous definition of 'i' was here
Line 90: error: 'for' loop initial declaration used outside C99 mode


Create a new paste based on this one


Comments: