using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 數組
{
class Program
{
/*
* 數組是引用類型,線程不安全
*
* 多維數組訪問下標 : array[i,j,z]
*
*/
static void Main(string[] args)
{
//數組(求最大值及下標)定義一個整型數組,輸入10個整數到數組中,並將數組中最大值及下標輸出
GetMax();
//字符數組(正序輸出)定義一個字符數組,輸入10個字符到數組中,將字符數組內容逐個輸出
PrintArr();
//逆序輸出)定義一個字符數組,輸入10個字符到數組中,將字符數組內容倒序輸出
Reverse();
//二維數組(求對角線之和)輸入9個整數,構成3*3的矩陣,打印主對角線之和
DiagonalSum();
//數組(矩陣反轉)定義一個二維數組a[3][4],輸入整數到數組中,然後將a數組矩陣反轉後存入到b[4][3]數組中,並將b輸出
MatrixFlip();
//拓展array中foreach,使其符合鏈式編程思想
ArrayEx();
Console.ReadKey();
}
private static void ArrayEx()
{
int[] arr = new int[] { 232, 3222, 555, 66, 234, 53, 17, 845, 1045 };
arr.Foreach(p => Console.Write(p+","));
Console.WriteLine();
}
private static void MatrixFlip()
{
int[,] arr = new int[3, 4] { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };
int[,] arr2 = new int[4, 3];
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
arr2[j, i] = arr[i, j];
}
}
for (int i = 0; i < arr2.GetLength(0); i++)
{
for (int j = 0; j < arr2.GetLength(1); j++)
{
Console.Write(arr2[i, j] + ",");
}
Console.WriteLine();
}
}
private static void DiagonalSum()
{
int[,] arr = new int[3, 3] { { 11, 12, 13 }, { 14, 15, 16 }, { 17, 18, 19 } };
int sum = 0;
Console.WriteLine();
for (int i = 0; i < arr.GetLength(0); i++)
{
for (int j = 0; j < arr.GetLength(1); j++)
{
if (i == j)
{
sum += arr[i, j];//注意多維數組的訪問方法
}
}
}
Console.WriteLine("sum:" + sum);
}
private static void Reverse()
{
char[] arr = new char[] { 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
char temp;
for (int i = arr.Length - 1, j = 0; i > arr.Length / 2; i--, j++)
{
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
Console.WriteLine("倒敘輸出:");
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + ",");
}
}
private static void PrintArr()
{
char[] arr = new char[] { 'q', 'w', 'r', 't', 'y', 'u', 'i', 'o', 'p' };
Console.Write("字符對應其ascll,");
foreach (char item in arr)
{
Console.Write(string.Format("{0}->{1},", item, (int)item));
}
}
private static void GetMax()
{
int[] arr = new Int32[] { 23237, 3232, 15435, 323230, 22545, 2342344, 23423411, 323237, 323255, 443, 7, 22, 7, 86, 3, 56, 6, 3, 754, 43, 23234, 4656, 22323 };
int max = 0;
int index = -1;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i]>max)
{
max = arr[i];
index = i;
}
}
Console.WriteLine(string.Format("數組中最大值爲{0},下標爲{1}", max, index));
}
}
public static class ArrayEx
{
public static void Foreach<T>(this IList<T> arr, Action<T> action)
{
foreach (var item in arr)
{
if (action!=null)
{
action(item);
}
}
}
}
}