】二维数组 衡行纵列
int[,] arr = new int[2,3]{{2,3,4},{5,6,7}}; //2行 3列 动态初始化
int[,] arr_1 = new int[,]{{1,3},{4,5},{6,7}}; //3行 2列
int[,] arr_2 = {{12,34,45},{32,16,25} }; //2行 3列 静态初始化
for (int i = 0; i < 2; i++) { //行数
for (int j = 0; j < 3; j++) { //列数
Console.Write("{0} ",arr[i,j]);
}
Console.WriteLine (); //换行
}
二维数组中,第n个元素对应的值为
int [a,b];
i = (n-1)/b;
j = (n-1)%b;
两行三列 => 三行两列
int[,] arr = new int[2,3]{{2,3,4},{5,6,7}};
int[,] arr_1 = new int[3,2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
arr_1[j,i] = arr[i,j]; //行列交换
}
}
for (int a = 0; a < 3; a++) { //遍历数组 打印
for (int b = 0; b < 2; b++) {
Console.Write("{0} ",arr_1[a,b]);
}
Console.WriteLine ();
}
//求最大元素及所在行和列
int[,] arr_1 = new int[,]{{1,3,5,6},{5,6,4,5},{6,7,5,8}};
//记录最大值及所在的下标
int max = arr_1 [0, 0], x=0, y=0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
if (max <arr_1[i,j]){
max = arr_[i,j];
x=i; //确定下标
y=j;
}
}
}
Console.WriteLine ("max= "+max+"x= "+x+"y= "+y);
对角线元素和
int sum = 0;
int[,] arr = new int[3, 3]{{1,2,3},{4,5,6},{7,8,9} };
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
sum += arr[i,j];
}
}
}
Console.WriteLine ("{0}",sum);
交错数组
类型 [ ] [ ] 数组名 = new 类型 [数组长度][ ];
例如 int [ ] [ ] arr = new int[3][ ];
int[ ] arr_1 = {1,3,5 };
int[ ] arr_2 = {2,4 };
int[ ] arr_3 = {23,45,12,34 };
int [ ][ ] arr = new int[3][ ]{arr_1,arr_2,arr_3};
arr [0] = new int[ ]{27,23,56 }; //修改下标为0的元素
arr [1] = arr_3; //使下标为1的元素等于arr_3的元素
//遍历数组
for (int i = 0; i < arr.Length; i++) {
for (int j = 0; j < arr[i].Length; j++) {
Console.Write ("{0} ",arr[i][j]);
}
Console.WriteLine();
}
foreach遍历数组
int[ ] arr = {1,2,5,6,8,7};
int sum = 1;
foreach (var a in arr) { //a不能进行修改
sum *= a;
}
Console.WriteLine ("{0}",sum);
string str = "Hello,lanou!";
char[ ] chars = str.ToCharArray(); //得到字符串的字符数组
//char[ ] chars_1 = "Hello,lanou!".ToCharArray();
int sum = 0;
for (int i = 0; i < chars.Length; i++) {
if (chars[i] =='l') {
++sum
}
}
Console.WriteLine ("{0}",sum);
string str = "Hello,lanou!";
char[ ] chars = str.ToCharArray();
// char[ ] chars_1 = "Hello,lanou!".ToCharArray();
int sum = 0;
foreach (var ch in chars) {
if (ch == 'l') {
++sum;
}
Console.WriteLine ("{0}",sum);