一維二維數組的創建與遍歷

一、一維數組的創建與遍歷
方法一:
類型[ ]變量=new 類型[ ];l例如:string a=new string[ var int]
若使用new關鍵字,則方括號內必須聲明一個int類型的值來表示長度
也可以:string[ ] a=new string[ ]{ }
方法二:
string[ ] a={"a","b","c","d"};
一維數組的遍歷:for和foreach
using System;
namespace practice3
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string[] a = new string[]{ "huang""jun""kai""h""j""k" };
            for (int i = 0; i < a.Length; i++)
            {
                Console.WriteLine (a[i]);
            }
            foreach (string item in a) 
            {
                Console.WriteLine (item);
            }
        }
    }
}
二、二維數組的創建與遍歷
方法一:
string[,] a=new string[5,3]
string[,] a=new string[5,3]{ {"a","b","c"},{"d","e","f"},{"g","h","i"},{"j","k","i"},{"l","m","n"}};
方法二:
string[, ] a={ {"a","b","c"},{"d","e","f"},{"g","h","i"},{"j","k","i"},{"l","m","n"}};
二維數組的遍歷:for和foreach
知識點:GetUpperBound(int variable>維度數字<);獲取指定維度的上限
GetLowerBound(int variable>維度數字<);獲取指定維度的下限
using System;
namespace practice3
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string[,] a = new string[,]
            { { "張三""男""18" }, { "李四""女""19" }, { "王五""男""18" } };
            for (int i = 0; i < a.GetUpperBound (0)+1; i++) 
            {
                for (int j = 0; j < a.GetUpperBound (1)+1; j++) 
                {
                    Console.Write(a[i,j]+"\t");
                }
                Console.WriteLine ();
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章