c#基础知识第五节
数组的定义
using System;
class program
{
static void Main(sting [ ] args)
{
//定义一个int类型的数组x
int [ ] x;
//指定数组x中有3个元素
x =new int [3];
//上面的两句合并成一句:int [ ] x=new int [3];
//设置第二个元素为1
x [0] =1;
//设置第二个元素为3
x [1] =3;
//设置第二个元素为5
x [2] =5;
Console.WriteLine("数组x中的第一个元素是"+ x[0]);
Console.WriteLine("数组x中共有“‘+x.Length +"个元素");
}
}
数组的遍历
using System;
class program
{
static void Main(sting [ ] args)
{
int [ ] x ={1,3,5};
for ( int i =0 ;i < x.Length; i++)
{
Console.WriteLine( x [i] );
}
}
}
using System;
class program
{
static void Main(sting [ ] args)
{
int [ ] x ={1,3,5};
foreach ( int i in x)
{
Console.WriteLine( i );
}
}
}
数组的最值
using System;
class Program
{
static void Main(string[] args)
{
int [ ] x = {1,3,6,10,12};
int min = x[0], max = x[0];
for (int i = 0; i < x.Length; i++)
{
if (max < x[i])
{
max = x[i];
}
if (min > x[i])
{
max = x[i];
}
}
Console.WriteLine("最小值是:"+min);
Console.WriteLine("最大值是:"+max);
Console.ReadKey();
}
}