CSharp · Console
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Tính giá trị lớn nhất, nhỏ nhất, trung bình và tổng của dãy phần tử");
int min, max, sum, avg, n;
Console.WriteLine("Nhập vào số phần tử mảng:");
n = int.Parse(Console.ReadLine());
//Khởi tạo mảng
int [] a = new int[n];
//Nhập dữ liệu cho từng phần tử mảng, chỉ số mảng bắt đầu từ 0
for(int i=0; i<n; i++)
{
Console.Write("a[{0}]:",i);
a[i] = int.Parse(Console.ReadLine());
}
Console.WriteLine("Chọn chức năng thực hiện:");
Console.WriteLine("1 - Tìm giá trị nhỏ nhất");
Console.WriteLine("2 - Tìm giá trị lớn nhất");
Console.WriteLine("3 - Tính tổng");
Console.WriteLine("4 - Tính trung bình");
Console.WriteLine("q - Kết thúc");
string chon = Console.ReadLine();
do
{
switch(chon)
{
case "1":
min = a[0];
for(int i=1;i<n;i++)
{
if(min>a[i])
min = a[i];
}
Console.WriteLine("Giá trị nhỏ nhất: {0}", min);
break;
case "2":
max=a[0];
for(int i=1;i<n;i++)
{
if(max<a[i])
max=a[i];
}
Console.WriteLine("Giá trị lớn nhất: {0}", max);
break;
case "3":
sum = 0;
for(int i=0;i<n;i++)
{
sum = sum + a[i];
}
Console.WriteLine("Tổng các phần tử: {0}",sum);
break;
case "4":
sum = 0;
for(int i=0;i<n;i++)
{
sum = sum+a[i];
}
avg=sum/n;
Console.WriteLine("Trung bình các phần tử: {0}",avg);
break;
default:
Console.WriteLine("Chức năng không hợp lệ\n");
break;
}
//Hiển thị lại menu để chọn
Console.WriteLine("Chọn chức năng thực hiện:");
Console.WriteLine("1 - Tìm giá trị nhỏ nhất");
Console.WriteLine("2 - Tìm giá trị lớn nhất");
Console.WriteLine("3 - Tính tổng");
Console.WriteLine("4 - Tính trung bình");
Console.WriteLine("q - Kết thúc");
chon = Console.ReadLine();
}
while(chon != "q");
}
}