2.1数组的概念
数组是具有相同数据类型的一组数据的集合。数组中的每一个变量称为数组的元素,数组能够容纳元素的数量称为数组的长度。
int[ ] a = new int[80];
数据类型 标识符 [正整数常量];
数组元素的基本数据类型 数组名 也可以是一个常量表达式
2.2一维数组
1、语法
数组元素类型 [ ] 数组名字;
int[ ]arr;
string[ ]arr;
2、初始化一维数组
初始化:就是给数组赋初值。
三种初始化方法
(1)int[]a= new int[3];
a[0]=7; //第一个元素从0开始
a[1]=8;
a[2]=9;
(2)int[ ]b=gew int[ ]{4,5,6};
(3)int[ ]c={1,2,3};
4、内存中的数组存储形式
int[ ]a = new int[3];
a[0]=7;
a[1]=8;
a[2]=9;
注:int[ ]array=hew int[(5]{0,1,2); //声明并初始化一维数组
代码错误 初始值的个数必须与数组的长度一样!
例:使用一维数组输出每个月的天数。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[12] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
for (int i = 0; i < 12; i++)
{
Console.WriteLine((i + 1) + "月有" + arr[i] + "天");
}
Console.Read();
}
}
}
2.3二维数组
1、语法
数据类型[ , ]数组名;
数据类型[ ][ ]数组名;
int[ , ]arr;
string[ ][ ] arr;
2、初始化二维数组
三种方法
(1)int[ , ]myarr = new int[2,2];
myarr[0,0]=0;
myarr[0,1]=1;
myarr[1,0]=1;
myarr[1,1]=2;
(2)int[ ][ ]myarr=new int[2][];
myarr[0]=new int[ ]{0,1};
myarr[1]=new int[ ]{1,2};
(3)int[ , ]myarr =new int[2,2]{{12,0},{45,10}};或
int[ , ] myarr=new int[ , ]{{12,0 },{45,10 }};或
int[ , ]myarr ={{12,0},{45,10}};
例:将二维数组中行数据和列数据调换位置。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
int[,] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Console.WriteLine("----------原始数组-----------");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine(arr[i,j] + " ");
}
Console.WriteLine();
}
int temp;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < i; j++)
{
temp = arr[i,j];
arr[i,j] = arr[j,i];
arr[j,i] = temp;
}
}
Console.WriteLine("--------调换之后的数组--------");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.WriteLine(arr[i,j] + " ");
}
Console.WriteLine();
}
Console.Read();
}
}
}
2.4不规则数组
int[ ][ ]a=new int[3][ ];
a[0]=new int[5];
a[1]=new int[3];
a[2]=new int[4];