数组定义
定义数组并赋值
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("你所删除的元素不存在!");
}
|
请发表评论