Mục đích:
Sử dụng mảng một chiều
Yêu cầu:
Thiết kế Form như hình sau:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Bai03
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//khai bao
private const int Max_Size = 10;
private int[] intArray;
//form load
private void Form1_Load(object sender, EventArgs e)
{
intArray = new int[Max_Size];
}
public void TaoMangNgauNhien()
{
Random r = new Random();
for(int i = 0; i< intArray.Length;i++)
{
intArray[i] = r.Next(1, 101);
}
}
public void XuatMang(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
txtMangGoc.Text += " " + a[i].ToString();
}
}
public int TongMang(int[] a)
{
int kq = 0;
for (int i = 0; i < a.Length; i++)
{
kq += a[i];
}
return kq;
}
public int FindMin(int[] a)
{
int min = a[0];
for (int i = 1; i < a.Length; i++)
{
if(a[i]<min)
{
min = a[i];
}
}
return min;
}
public void TangMoiPhanTuMangLen2(int[] a)
{
txtKetQua.Clear();
for (int i = 0; i < a.Length; i++)
{
a[i] += 2;
txtKetQua.Text += " " + a[i].ToString();
}
}
public int SoPhanTuLe(int[] a)
{
int dem = 0;
for (int i = 0; i < a.Length; i++)
{
if(a[i]%2==1)
{
dem++;
}
}
return dem;
}
public int TongPhanTuLe(int[] a)
{
int tongle = 0;
for (int i = 0; i < a.Length; i++)
{
if (a[i] % 2 == 1)
{
tongle+= a[i];
}
}
return tongle;
}
public void SapMangTang(int[] a)
{
for (int i = 0; i < a.Length-1; i++)
{
for(int j = i+1;j<a.Length;j++)
{
if(a[i]>a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
public void SapMangGiam(int[] a)
{
for (int i = 0; i < a.Length - 1; i++)
{
for (int j = i + 1; j < a.Length; j++)
{
if (a[i] < a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
private void btnXuatMangNgauNhien_Click(object sender, EventArgs e)
{
TaoMangNgauNhien();
XuatMang(intArray);
}
private void btnTimPTNhoNhat_Click(object sender, EventArgs e)
{
txtKetQua.Text = FindMin(intArray).ToString();
}
private void btnTinhTongGiaTriMang_Click(object sender, EventArgs e)
{
txtKetQua.Text = TongMang(intArray).ToString();
}
private void btnTangMoiPTLen2_Click(object sender, EventArgs e)
{
TangMoiPhanTuMangLen2(intArray);
}
private void btnDemSoPTLe_Click(object sender, EventArgs e)
{
txtKetQua.Text = SoPhanTuLe(intArray).ToString();
}
private void btnTongGiaTriPTLe_Click(object sender, EventArgs e)
{
txtKetQua.Text = TongPhanTuLe(intArray).ToString();
}
private void btnSapMangTang_Click(object sender, EventArgs e)
{
SapMangTang(intArray);
HienThiMang(intArray);
}
public void HienThiMang(int[] a)
{
txtKetQua.Clear();
for (int i = 0; i < a.Length; i++)
{
txtKetQua.Text += " " + a[i].ToString();
}
}
private void btnSapMangGiam_Click(object sender, EventArgs e)
{
SapMangGiam(intArray);
HienThiMang(intArray);
}
}
}