본문 바로가기
C#(CSharp)/기초강좌(Basic)

[13] C# 배열 (C# Array and foreach)

by swconsulting 2015. 2. 23.

배열 [...]

고정된 사이즈로 이루어진 동일한 종류 collection data 모음입니다. 여기서 List와 다르게 중요한 점은 사이즈 크기가 고정된다는 점 입니다. 크기가 고정된 대신 속도는 List 보다 빠릅니다.


솔직히 글로 설명은 힘듭니다. 그래서 아래 2개 이미지를 보시면 좀더 이해가 쉬울 것입니다.







위 그림처럼 메모리에도 순서대로 값이 올라가 있습니다. 이점 때문에 list 보다 속도가 빠른 이유 입니다.


1) 배열 선언 및 초기화

datatype[] arrayName;
double[] balance = new double[10];

2) 배열에 값을 할당

double[] balance = new double[10];
balance[0] = 4500.0;
double[] balance = { 2340.0, 4523.69, 3421.0};
int [] marks = new int[]  { 99,  98, 92, 97, 95};
int[] score = marks;

3) 반복문(Loop)에서 배열 활용

using System;

namespace ArrayApplication
{
   class MyArray
   {
      static void Main(string[] args)
      {
         int []  n = new int[10]; /* n is an array of 10 integers */


         /* initialize elements of array n */         
         for ( int i = 0; i < 10; i++ )
         {
            n[i] = i + 100;
         }

         /* output each array element's value */
         foreach (int j in n )
         {
            int i = j-100;
            Console.WriteLine("Element[{0}] = {1}", i, j);
            i++;
         }
         Console.ReadKey();
      }
   }
}
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109


4) 배열을 메소드 파라미터로 전달하기

using System;

namespace ArrayApplication
{
   class ParamArray
   {
      public int AddElements(params int[] arr)
      {
         int sum = 0;
         foreach (int i in arr)
         {
            sum += i;
         }
         return sum;
      }
   }
      
   class TestClass
   {
      static void Main(string[] args)
      {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(512, 720, 250, 567, 889);
         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}
The sum is: 2938



참고 : http://www.tutorialspoint.com/csharp/index.htm