1、设计一个数组用于存放10个整数,然后计算这十个整数之和?
private void btn1_Click(object sender, EventArgs e) { int temp = 0; lblResult.Text = "";//初始清空内容 //题目:存放10个整数然后求和 int[] a = new int[10] { 9, 8, 2, 3, 5 ,6,4,2,7,3}; lblResult.Text += "\n a数组元素初始值:"; for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } lblResult.Text += "\n 求和结果:"; for (int i = 0; i < a.Length; i++) { temp += a[i]; } lblResult.Text += temp.ToString(); }
2、设计一个数组用于存放10个整数,然后计算数组中顺序为偶数的元素之和?
注意:顺序为偶数是不是下标为偶数?
private void btn2_Click(object sender, EventArgs e) { int temp = 0; lblResult.Text = "";//初始清空内容 //题目:存放10个整数然后求和 int[] a = new int[10] { 9, 8, 2, 3, 5, 6, 4, 2, 7, 3 }; lblResult.Text += "\n a数组元素初始值:"; for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } lblResult.Text += "\n 求和结果:"; for (int i = 0; i < a.Length; i++) { if(i%2==0) temp += a[i]; } lblResult.Text += temp.ToString(); }
3、练习使用Array常用的属性和方法,例如length 属性,Sort 、Reverse方法。对给定数组进行排序,获取元素个数等?
private void btnEnter_Click(object sender, EventArgs e) { lblResult.Text = "";//初始清空内容 int[] a = new int[5] {9,8,2,3,5}; lblResult.Text += "\n a数组元素初始值:"; for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } lblResult.Text += "\n a数组元素长度:"+a.Length.ToString(); Array.Sort(a);//对数组(Array)进行排序 lblResult.Text += "\n 使用Sort进行排序:"+a[0].ToString() + "," + a[1].ToString() + "," + a[2].ToString() + "," + a[3].ToString() + "," + a[4].ToString()+"\n 使用Reverse反转:"; Array.Reverse(a);//反转排序 for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } }
4、如何实现一维数组的元素降序排列?
private void btnEnter2_Click(object sender, EventArgs e) { lblResult.Text = "";//初始清空内容 //题目:如何实现一维数组降序排列 int[] a = new int[5] { 9, 8, 2, 3, 5 }; lblResult.Text += "\n a数组元素初始值:"; for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } lblResult.Text += "\n 对a进行降序排序:" ; Array.Sort(a);//对数组(Array)进行排序 if(a[0]<a[a.Length-1]) Array.Reverse(a);//如果第一个值小于最后一个值,说明是升序,则反转排序 for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } }
5、定义一个4行3列二维数组,并访问其中左下角的元素?
private void btnEnter2_Click(object sender, EventArgs e) { lblResult.Text = "";//初始清空内容 //题目:如何实现一维数组降序排列 int[] a = new int[5] { 9, 8, 2, 3, 5 }; lblResult.Text += "\n a数组元素初始值:"; for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } lblResult.Text += "\n 对a进行降序排序:" ; Array.Sort(a);//对数组(Array)进行排序 if(a[0]<a[a.Length-1]) Array.Reverse(a);//如果第一个值小于最后一个值,说明是升序,则反转排序 for (int i = 0; i < a.Length; i++) { lblResult.Text += a[i].ToString() + ","; } }