2D Arrays Basics
Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 1번째.
C#에서 가변 배열은 배열의 배열로, 격자 또는 행렬과 유사한 구조를 형성합니다. 행과 열이 있는 테이블과 같으며, 각 셀은 값을 저장할 수 있습니다. 가변 배열은 체스판, 좌석 배치도, 또는 격자 기반 게임과 같은 2차원 관계를 가진 데이터를 표현하는 데 유용합니다.
C#에서 가변 배열을 선언하고 초기화하는 방법은 다음과 같습니다:
data_type[][] arrayName = new dataType[numberOfRows][];dataType: 배열이 담을 요소의 타입 (e.g., int, string 등).
arrayName: 배열에 부여하는 이름.
numberOfRows: 배열의 행 수.
각 행은 그 후 개별적으로 초기화되어야 합니다:
arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];
// and so on...예를 들어, 각 행이 4개의 열을 가진 3행의 정수형 가변 배열을 생성하려면 다음과 같이 작성합니다:
int[][] matrix = new int[3][];
matrix[0] = new int[4];
matrix[1] = new int[4];
matrix[2] = new int[4];가변 배열(jagged array)을 값으로 직접 초기화할 수도 있습니다:
int[][] matrix = new int[][] {
new int[] {1, 2, 3},
new int[] {4, 5, 6},
new int[] {7, 8, 9}
};챌린지
쉬움다음 값으로 가변 배열을 초기화하세요:
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이 정확한 값들로 가변 배열을 올바르게 초기화하고 프로그램이 행렬을 올바르게 출력하도록 하는 것이 당신의 임무입니다.
치트 시트
가변 배열은 배열의 배열로, 행과 열을 가진 매트릭스와 같은 구조를 형성합니다.
선언 구문:
data_type[][] arrayName = new dataType[numberOfRows][];각 행은 별도로 초기화해야 합니다:
arrayName[0] = new dataType[lengthOfFirstRow];
arrayName[1] = new dataType[lengthOfSecondRow];별도 초기화 예제:
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}
};직접 해보기
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