概念:定義一組同類型的指定個數的變量,索引從0開始
例:
int[] shuname = new int[10];//定義一組有10個數據的數組 shuname[0] = 1; Console.WriteLine(shuname[0]);//打印出1
數組與for循環結合的練習:
1、彩票問題:通過數組錄入隨機生成的紅球。
//定義一個含有6個數據的數組
int[] hongqiu = new int[6];
Random r = new Random();
//隨機生成紅球的方法
for (int i = 0; i < 6; i++)
{
hongqiu[i] = r.Next(1, 34);
for (int j = 0; j < i; j++)
{
if (hongqiu[i] == hongqiu[j])
{
//判斷是否出現重復的紅球,若出現就i--再重復循環
i--;
break;
}
}
}
Console.WriteLine("紅球為:");
//打印出來紅球
for (int i = 0; i < 6; i++)
{
Console.Write("{0} ", hongqiu[i]);
}
//隨機生成一個藍球
int blue;
while(true)
{
blue = r.Next(1,17);
for(int i = 0;i<6;i++)
{
//判斷藍球是否與紅球中任意一數重復
if (blue != hongqiu[i])
{
continue;
}
else
break;
}
break;
}
Console.WriteLine("藍球為:{0}", blue);
2、遍歷數組
for (int i = 0;i<hongqiu.Length;i++)
{
int h;
h = hongqiu[i];
Console.WriteLine(h);
}
hongqiu.Length是數組的元素個數
3、自動遍歷數組的方法:foreach
foreach (int p in hongqiu)//p的數據類型需要與數組保持一致
{
Console.WriteLine(p);
}
1、等量代換的思路:
int a = 0; int b = 1; //要交換a和b,需要一個中間變量c int c = a; a = b; b = c;
2、在數組中通過for循環的運用
思路:用兩層for循環嵌套:外層的for循環(從索引為0開始)給 i 一個數組中的值,
內層的for循環(從索引為 i 開始)給 j 一個數組中的值,並與 i 進行循環比較,最後排出想要的順序。
例:輸入五個人的成績,進行升序的冒泡排序
int[] shuzu = new int[5];
Console.WriteLine("請輸入五個人的成績:");
for (int i = 0; i < 5; i++)
{
shuzu[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < 5; i++)
{
for (int j = i+1; j < 5; j++)
{
if (shuzu[i] > shuzu[j])
{
int zhong = shuzu[j];
shuzu[j] = shuzu[i];
shuzu[i] = zhong;
}
}
}
foreach (int a in shuzu)
{
Console.WriteLine(a);
}