2D Arrays Basics
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 1번째.
C#에서 가변 배열(jagged array)은 배열의 배열로, 그리드나 행렬과 같은 구조를 형성합니다. 이는 행과 열이 있는 표와 같으며, 각 셀은 값을 가질 수 있습니다. 가변 배열은 체스판, 좌석 배치도 또는 그리드 기반 게임과 같이 2차원 관계를 가진 데이터를 표현하는 데 유용합니다.
C#에서 가변 배열(jagged array)을 선언하고 초기화하는 방법은 다음과 같습니다:
data_type[][] arrayName = new dataType[numberOfRows][];dataType: 배열이 보유할 요소의 유형입니다 (예: int, string 등).
arrayName: 배열에 부여하는 이름입니다.
numberOfRows: 배열의 행 수입니다.
그런 다음 각 행을 별도로 초기화해야 합니다:
arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];
// 이런 식으로 계속됩니다...예를 들어, 각 행이 4개의 열을 갖는 3개 행의 정수 가변 배열(jagged array)을 만들려면 다음과 같이 작성합니다:
int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];가변 배열을 값으로 직접 초기화할 수도 있습니다:
int[][] matrix = new int[][] {
new int[] {1, 2, 3},
new int[] {4, 5, 6},
new int[] {7, 8, 9}
};참고: 이 플랫폼은 C# 12 이전 버전의 컴파일러를 사용합니다. C# 12에서 도입된 더 짧은 컬렉션 식 구문(예: int[][] matrix = [[1, 2], [3, 4]];)은 여기서 지원되지 않습니다. 위에 표시된 기존의 new int[][] { ... } 초기화 구문을 사용해 주세요.
챌린지
쉬움다음 값들을 사용하여 가변 배열(jagged array)을 초기화하세요:
5, 7, 10, 24, 41
86, 13, 683, 64, 13
42, 46, 791, 111, 9
86, 88, 1845, 5, 15897
9, 1, 5, 5, 6여러분의 과제는 이 정확한 값들로 가변 배열을 올바르게 초기화하고, 프로그램이 행렬을 올바르게 출력하도록 하는 것입니다.
참고: 이 플랫폼은 C# 12 이전 버전의 컴파일러를 사용합니다. C# 12의 컬렉션 식 구문(예: int[][] matrix = [[1, 2], [3, 4]];)은 지원되지 않습니다. 대신 다음과 같은 전통적인 초기화 구문을 사용하세요:int[][] matrix = new int[][] { new int[] {1, 2}, new int[] {3, 4} };
직접 해보기
using System;
class Program
{
static void Main(string[] args)
{
int[][] matrix = {
// 여기에 코드를 작성하세요
};
// 행렬을 출력합니다
int rows = matrix.Length;
for (int i = 0; i < rows; i++)
{
int cols = matrix[i].Length;
for (int j = 0; j < cols; j++)
{
Console.Write(matrix[i][j] + " ");
}
Console.WriteLine();
}
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
논리 및 흐름의 모든 레슨
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety