[C#] Ví dụ 1 – Làm việc với tập tin
Thuật toán:
– Nhập n
– Tạo mới file
– j=1..n
+ i=1..n
~ Ghi i vào file
+ Xuống dòng
– Đóng file
Bài giải:
– Hàm nhap(n): thực hiện việc nhập từ bàn phím một số nguyên n
– Hàm xuly(n): thực hiện xử lý bài toán theo yêu cầu và ghi kết quả vào file data.out
class Program
{
static void Main(string[] args)
{
int n;
nhap(out n);
xuly(n);
}
static void nhap(out int n)
{
Console.Write(“n= “);
n = int.Parse(Console.ReadLine());
}
static void xuly(int n)
{
//Bước 1: Tạo mới tập tin
StreamWriter f = new StreamWriter(“data.out”);
//Bước 2: Ghi dữ liệu ra tập tin
int j, i;
for (j = 1; j <= n; j++)
{
for (i = 1; i <= n; i++)
f.Write(i + ” “);
f.WriteLine();
}
//Bước 3: Đóng tập tin
f.Close();
Console.Write(“Da hoan thanh!!!”);
Console.ReadKey();
}
}
Hits: 55