C#各種數組的用法實例演示
更新時間:2014年07月17日 12:03:54 投稿:shichen2014
這篇文章主要介紹了C#各種數組的用法,有助于初學者學習并鞏固C#關于數組的用法,需要的朋友可以參考下
本文以實例演示了C#各種數組的基本用法。主要包括:一維數組、二維數組、鋸齒型數組、長度不同的兩個數組、3行4列的矩陣數組等。
具體實現代碼如下:
using System;
class ArrayApp
{
public static void Main ( )
{
//一維數組用法:計算數組中奇偶數的個數
Console.WriteLine("一維數組演示:一維數組中的奇偶數個數");
int[ ] arr1 = new int[ ] {8, 13, 36, 30, 9, 23, 47, 81 };
int odd = 0;
int even = 0;
foreach ( int i in arr1 )
{
if ( i % 2 == 0 )
even ++;
else
odd ++;
}
Console.WriteLine("共有 {0} 個偶數, {1} 個奇數。", even, odd);
//二維數組用法:m行n列的矩陣
Console.WriteLine("二維數組演示:3行4列的矩陣");
int[,] arr2 = new int[3,4] { {4,2,1,7}, {1,5,4,9}, {1,3,1,4} };
for ( int i = 0; i < 3; i++ )
{
for ( int j = 0; j < 4; j++ )
{
Console.Write(arr2[i,j] + "\t");
}
Console.WriteLine( );
}
//鋸齒型數組用法:元素個數不同的兩個數組
Console.WriteLine("鋸齒型數組演示:長度不同的兩個數組");
int[][] arr3 = new int[2][];
arr3[0] = new int[5] {1,3,5,7,9};
arr3[1] = new int[4] {2,4,6,8};
// char[][] arr3 = new char[][] { {H,e,l,l,o}, {C,s,h,a,r,p} };
for ( int i = 0; i < arr3.Length; i++)
{
Console.Write("第{0}個數組是:\t",i+1);
for ( int j = 0; j < arr3[i].Length; j++ )
{
Console.Write(arr3[i][j]+ "\t");
}
Console.WriteLine();
}
}
}

