C#遍歷數組


Eg:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace ConsoleApplication1
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             //聲明數組. 第一種方法. 聲明並分配元素大小.
13             int[] Myint = new int[30];
14             Myint[0] = 30;
15             Myint[1] = 50;
16             // 以此類推, 起始下標為0
17             //-------------------------------
18             // 聲明數組,第二種方法, 聲明並直接賦值,沒有指定元素大小.
19             int[] Myint1 = { 20,10,50,65,18,90}; 
20             //------------------------------------------
21             //聲明數組,第三種方法, 聲明並分配大小,且賦值.
22             int[] i = new int[5] { 10, 20, 30, 40, 50 };
23 
24             // -----------------------------------------------
25             // foreach循環遍歷數組..
26             int[] Sum = new int[50];
27             Random rd = new Random();
28            // 先用for循環給數組取隨機數.
29             for (int s = 0; s <= Sum.Length - 1; s++)  // Sum.Length是數組的一個屬性,Length代表數組的長度
30             {
31                 Sum[s] = rd.Next(100);
32             }
33            // 遍歷數組輸出
34             foreach (int t in Sum)
35             {
36                 Console.WriteLine(t);
37             }
38         }
39     }
40 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM