본문 바로가기

W3Schools C# 개인학습 (Array->Multidimensional Arrays)

@salmu2025. 5. 26. 17:34
반응형

1. Array 

string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
Console.WriteLine(cars[0]);

 

 

2. counter (i) 카운터

:반복문에서 반복 횟수나 현재 위치(인덱스)를 추적하기 위해 사용하는 변수

주로 for, while 의 loop에서 사용

 

 

 

 

3. foreach (counter 필요 없는 반복문)

:자동으로 배열을 처음부터 끝까지 순회

 

[구조]

foreach (데이터 in 배열)
{
    // 요소 하나씩 자동으로 꺼내 씀
}

 

 

 

[예시]

string[] colors = { "red", "green", "blue" };

foreach (string color in colors)
{
    Console.WriteLine(color);
}

 

 

 

4. Sort()

  •  List<T>.Sort() – 리스트 자체를 정렬 (제자리 정렬) 
  • int, string 등 기본형에 대해 자동으로 오름차순 정렬
List<int> numbers = new List<int>() { 3, 1, 4 };
numbers.Sort(); // 오름차순 정렬: 1, 3, 4

 

 

  • 배열 정렬 Array.Sort()
int[] numbers = { 9, 3, 1 };
Array.Sort(numbers); // 배열 자체가 오름차순 정렬됨

 

 

 

5. 다차원 배열

int[,] numbers = { {1, 4, 2}, {3, 6, 8} };

 

int [,]  -> , 한개 = 2차원 배열

행(row) / 열(column)

numbers[0, 0] = 1   numbers[0, 1] = 4   numbers[0, 2] = 2  
numbers[1, 0] = 3   numbers[1, 1] = 6   numbers[1, 2] = 8

 

3차원 배열 -> ,, 두개

int[,,] cube = new int[2, 2, 2]
{
    {
        {1, 2}, {3, 4}
    },
    {
        {5, 6}, {7, 8}
    }
};

 

* 몇번째 셀 때 0부터 시작하는 것 주의

 

 

 

6. GetLength()

:다차원 배열의 특정 차원의 크기를 구할 때 사용하는 메서드

단일 배열에서는 .Length를 주로 사용하고, 2차원 이상일 때는 GetLength(차원)

 

array.Length 전체 요소 수 (모든 차원 포함)
array.GetLength(n) n번째 차원의 길이 (0부터 시작)

 

 

 

 

반응형
salmu
@salmu :: SMU 각종 기록

목차