C# 기초

배열

배열은 같은 타입의 값을 정해진 개수만큼 저장하며, 각 값은 0부터 시작하는 인덱스로 접근합니다.

동작 원리

C# 배열을 만들고, 읽고, 바꾸고, 순회하고, 정렬합니다. 2차원 배열도 다룹니다.

Length는 크기를 알려 주고 ^1은 마지막 원소를 읽습니다. foreach는 모든 원소를 방문하고, Array.Sort는 제자리에서 정렬하며, new int[3]은 0으로 시작하고, int[,]는 행과 열로 접근하는 격자를 만듭니다.

동작 원리 보기

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

실행 가능한 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 리뷰를 받을 수 있습니다.

모든 챌린지