1. 程式人生 > >c#基礎知識第五節

c#基礎知識第五節

n) 基礎 ole 最大值 new rgs sys 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();
}
}

c#基礎知識第五節