1. 程式人生 > >C#基礎-數組

C#基礎-數組

class 中新 num str int 新的 mes length 最大值最小值

數組定義

定義數組並賦值

int[] scores = { 45, 56, 78, 98, 100 };     //在定義數組時賦值
for(int i = 0; i < scores.Length; i++)
{
   Console.WriteLine(scores[i]);
}

定義數組不賦值

string[] stuNames = new string[3];
stuNames[0] = "jame";
stuNames[1] = "max";
stuNames[2] = "joe";

一維數組應用

求數組的和

int[] nums = new int[] { 23, 67, 35, 24, 67 };
int sum = 0;
for(int i = 0; i < nums.Length; i++)
{
    sum += nums[i];
}
Console.WriteLine("數字之和為:{0}",sum);

倒序輸出

int[] intNums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int i = intNums.Length - 1; i >= 0; i--)
{
    Console.WriteLine(intNums[i]);
}

求最大值最小值

int[] intN = { 23, 67, 35, 24, 67 };
int max = intN[0];
int min = intN[0];
for (int i = 0; i < intN.Length; i++)
{
    if (max < intN[i])
    {
        max = intN[i];
    }
    if (min > intN[i])
    {
        min = intN[i];
    }
}
Console.WriteLine("最大值:{0}  最小值:{1}", max, min);

在原有數組中新增

int[] arrS = new int[4] { 12, 13, 14, 15 };
int[] tmp = new int[arrS.Length + 1];   //新增一個數據
for(int i = 0; i < arrS.Length; i++)
{
    tmp[i] = arrS[i];
}
Console.WriteLine("輸入新增的數據");
int addNum = Convert.ToInt32(Console.ReadLine());
tmp[tmp.Length - 1] = addNum;
arrS = tmp;
Console.WriteLine("輸出新的數據:");
for(int i = 0; i < arrS.Length; i++)
{
    Console.WriteLine(arrS[i]);
}

新增與刪除操作

刪除數組中的一個元素
原理:
1.找出刪除元素索引
2.索引前的元素直接賦值到臨時數組中,索引後的數組在原有數組後索引+1後賦值

int[] arrS = new int[4] { 12, 13, 14, 15 };
Console.WriteLine("請輸入你要刪除的元素");
int getNum = Convert.ToInt32(Console.ReadLine());
int getIndex = -1;
for(int i = 0; i < arrS.Length; i++)
{
    if (getNum == arrS[i])
    {
        getIndex = i;
        break;
    }
}
if (getIndex >= 0)
{
    int[] tmp = new int[arrS.Length - 1];
    for(int i = 0; i < tmp.Length; i++)
    {
        if (i >= getIndex)
        {
            tmp[i] = arrS[i + 1];
        }
        else
        {
            tmp[i] = arrS[i];
        }
    }
    arrS = tmp;
    Console.WriteLine("刪除後的數據:");
    for(int i = 0; i < arrS.Length; i++)
    {
        Console.WriteLine(arrS[i]);
    }
}
else
{
    Console.WriteLine("你所刪除的元素不存在!");
}

C#基礎-數組