C# 기초

C#의 배열

이 레슨에서는 2차원 배열을 포함해 C#에서 배열을 만들고, 읽고, 바꾸고, 돌아보고, 정렬합니다.

소개

배열(array)은 같은 타입의 값을 정해진 개수만큼 저장합니다. 각 요소에는 0부터 시작하는 인덱스(index)로 접근합니다. 배열을 만든 뒤 각 요소의 값은 바꿀 수 있지만 길이는 바꿀 수 없습니다.

Length 속성은 요소의 개수를 주고, scores[^1]은 마지막 요소를 가져오는 짧은 표기입니다. foreach 반복문이 모든 요소를 돌며 합계와 평균을 계산합니다. Array.Sort는 배열을 제자리에서 정렬합니다. new int[3]으로 만든 배열에는 이미 0이 들어 있고, int[,] 타입은 행과 열로 접근하는 2차원 배열을 만듭니다.

동작 원리 보기

칸을 클릭하거나 슬라이더로 인덱스를 고르세요. 삽입이나 삭제를 해 보면 뒤의 모든 요소가 왜 밀려나야 하는지 알 수 있습니다.

실행 가능한 C# 예제

C#
코드 실행 →
Program.cs
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        // An array has a fixed length set when it is created.
        int[] scores = { 72, 95, 88, 64 };
        Console.WriteLine($"Length: {scores.Length}");
        Console.WriteLine($"First: {scores[0]}, last: {scores[^1]}");

        scores[3] = 70;  // elements can be changed, the length cannot

        int sum = 0;
        foreach (int score in scores)
        {
            sum += score;
        }
        Console.WriteLine($"Sum: {sum}, average: {sum / (double)scores.Length}");

        // Array.Sort sorts in place; string.Join prints the elements.
        Array.Sort(scores);
        Console.WriteLine($"Sorted: {string.Join(", ", scores)}");
        Console.WriteLine($"Max: {scores.Max()}");

        // new int[3] creates an array of zeros.
        int[] counts = new int[3];
        counts[1] = 5;
        Console.WriteLine($"Counts: {string.Join(" ", counts)}");

        // A 2D array is indexed by row and column.
        int[,] grid = { { 1, 2, 3 }, { 4, 5, 6 } };
        Console.WriteLine($"grid[1, 2] = {grid[1, 2]}");
    }
}
실행 결과
Length: 4
First: 72, last: 64
Sum: 325, average: 81.25
Sorted: 70, 72, 88, 95
Max: 95
Counts: 0 5 0
grid[1, 2] = 6

디버거로 연습하기

중요한 대입이나 조건에 중단점을 두고 Debug를 눌러 다음 줄로 넘어가기 전에 지역 변수 값을 확인하세요.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지