1、数组:定义一组同类型的指定个数的变量,索引从0开始。
(1)定义一个数组:
int[] shuzu = new int[10];
(2)赋值:
①int[] shuzu = new int[3]{1,2,3};
②int[] shuzu = new int[3];
shuzu[0]=1;
shuzu[1]=2;
shuzu[2]=3;
2、自动遍历数组
foreach循环语句
foreach(int a in shuzu)
{
Console.WriteLine(a);
}
3、等量代换:相等类型的两个变量,交换两个变量里的值。
int a=3,b=5;
int c;
c=a;
a=b;
b=c;
4、冒泡排序
for (int m = 0; m < 10; m++)
{
for (int n = 0; n < m; n++)
{
if (shuzu[m] > shuzu[n])
{
int zhong;
zhong = shuzu[m];
shuzu[m] = shuzu[n];
shuzu[n] = zhong;
}
}
}
例:
输入10人的分数,求最大值,最小值,平均分,总分
int[] fenshu = new int[10];
int zongfen = 0;
for (int m = 0; m < 10; m++)
{
Console.Write("请输入第{0}个人的分数:", m + 1);
fenshu[m] = int.Parse(Console.ReadLine());
zongfen = zongfen + fenshu[m];
}
for (int m = 0; m < 10; m++)
{
for (int n = 0; n < m; n++)
{
if (fenshu[m] > fenshu[n])
{
int zhong;
zhong = fenshu[m];
fenshu[m] = fenshu[n];
fenshu[n] = zhong;
}
}
}
Console.WriteLine("降序排列为:");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(fenshu[i]);
}
for (int m = 0; m < 10; m++)
{
for (int n = 0; n < m; n++)
{
if (fenshu[m] < fenshu[n])
{
int zhong;
zhong = fenshu[m];
fenshu[m] = fenshu[n];
fenshu[n] = zhong;
}
}
}
Console.WriteLine("升序排列为:");
for (int i = 0; i < 10; i++)
{
Console.WriteLine(fenshu[i]);
}
Console.WriteLine("最小值为:{0}
最大值为:{1}", fenshu[0], fenshu[9]);
double pingjunfen = 1.0 * zongfen / fenshu.Length;
Console.WriteLine("总分是:{0}
平均分是:{1}", zongfen, pingjunfen);