//一维数组【相同数据类型】
//第一种定义方式
// int[] shuzu = new int[5];
shuzu[0]=1;
shuzu[1]=2;
shuzu[2]=3;
shuzu[3]=4;
shuzu[4]=5;
for(int i=1;i<5;i++)
{
shuzu[i]=i+1;
}
//第二种定义方式
//int[] shuzu = new int[] { 1,2,3,4,5 };
//Console.WriteLine(shuzu[2]);
案例:
1. //从控制台输入10个人的年龄放入数组,
//将十个人的年龄求总和
int []shuzu= new int[10]; int sum = 0; for (int i = 0; i < 10; i++) { Console.Write("请输入第"+(i+1)+"个人年龄:"); shuzu[i] = int.Parse(Console.ReadLine()); sum += shuzu[i]; } Console.WriteLine("年龄总和为:" + sum); Console.ReadLine();
2. //输入人名放进数组,输出第5个人的姓名
Console.Write("请输入有多少人:"); int a = int.Parse(Console.ReadLine()); string[] name = new string[a]; if (a >= 5) { for (int i = 0; i < a; i++) { Console.Write("请输入第" + (i + 1) + "个人的名字:"); name[i] = Console.ReadLine(); } Console.WriteLine("第五个人的名字是:"+name[4]); } else { Console.WriteLine("您的输入有误!"); } Console.ReadLine();
3. //输入班级人数,根据人数,
//挨个输入成绩,求平均分
Console.Write("请输入班级人数:"); int a = int.Parse(Console.ReadLine()); double sum = 0; double[]chengji=new double[a]; for (int i = 0; i < a; i++) { Console.Write("请输入第"+(i+1)+"个人的成绩:"); chengji[i] = double.Parse(Console.ReadLine()); sum += chengji[i]; } Console.WriteLine("平均分为:"+(sum/a)); Console.ReadLine();
二维数组:(两种表达方式)
int[,] shuzu = new int[3, 4]; 有3个一维数组,每个一维数组有4个值。
int[,] shuzu = new int[,]
{
{1,2,3,4},
{5,6,7,8},
{6,7,8,9}
};
案例:
1. 用二维数组写“王”。
string[,] shuzu = new string[,] { {" ","■","■","■","■","■",""}, {" "," "," ","■","","",""}, {" "," "," ","■","","",""}, {" "," ","■","■","■","",""}, {" "," "," ","■"," "," ",""}, {" "," "," ","■"," "," ",""}, {"■","■","■","■","■","■","■"} }; for (int i = 0; i < 7; i++) { for (int j = 0; j < 7; j++) { Console.Write(shuzu[i, j]); } Console.WriteLine(); }
Console.ReadLine();
2. //输入班级人数,将每个人的
//语文,数学,英语成绩输入二维数组
Console.Write("请输入班级人数:"); int a = int.Parse(Console.ReadLine()); double[,] chengji = new double[a, 3]; for (int i = 0; i < a; i++) { for (int j = 0; j < 3; j++) { if (j == 0) { Console.Write("请输入第"+(i+1)+"个人的语文成绩:"); } if (j == 1) { Console.Write("请输入第" + (i + 1) + "个人的数学成绩:"); } if (j == 2) { Console.Write("请输入第" + (i + 1) + "个人的英语成绩:"); } chengji[i,j]=double.Parse(Console.ReadLine()); } } Console.ReadLine();
3. //使用二维数组打印“企”。
string[,] shuzu = new string[8, 7] { {" "," "," ","■"," "," "," "}, {" "," ","■"," ","■"," "," "}, {" ","■"," "," "," ","■"," "}, {"■"," "," ","■"," "," ","■"}, {" "," "," ","■"," "," "," "}, {" ","■"," ","■","■","■"," "}, {" ","■"," ","■"," "," "," "}, {"■","■","■","■","■","■","■"} }; for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { Console.Write(shuzu[i, j]); } Console.WriteLine(); } Console.ReadLine();
三维数组:
int[, ,] shuzu = new int[3, 2, 4]; 3个二维数组,每个二维数组有2个一维数组,每个一维数组有4个数值
{ { {1,2,3,4},{1,2,3,4} },{ {1,2,3,4},{1,2,3,4} },{ {1,2,3,4},{1,2,3,4} } }