전체 코드

using System.ComponentModel;
using System.Numerics;
using System.Threading;

namespace CSharp
{
    // 객체지향 문법을 활용한 TextRPG
    class Program
    {

        Player player;
        Monster monster;

        // 여러명의 몬스터를 만드려면
        // 1. 우선 변수를 여러개 만듬 -> 비효율적
        //Monster monster1;
        //Monster monster2;
        //Monster monster3;
        //Monster monster4;

        // 체크 하고 싶으면 if문도 여러개 만들어야됨
        // 따라서 이러한 방법은 사용할 수 없음
        // 즉 자료구조가 필요함

        // 배열


        static void Main(string[] args)
        {
            // 자료구조란
            // 자료에 대한 구조를 말함
            // 배열
            // 하나의 변수로 여러가지 데이터를 묶어서 관리가능
            // 하나의 타입의 자료형으로 밖에 사용할 수 없음

            int a;

            int[] scores = new int[] { 10,20,30,40,50 };    // 한 번만들면 변경 안됨
                                                            // 길이가 안맞으면 에러발생
                                                            // []의 숫자 생략 가능 컴파일이 몇개인지 추론함
                                                            
            // new 키워드를 통해서 참조 타입인것을 알 수 있음
            int[] scores2 = scores;
            
            scores[0] = 9999; // scores2[0] = 9999이다


            // 배열 문법1                            //
            //scores[0] = 10;
            //scores[1] = 20;
            //scores[2] = 30;
            //scores[3] = 40;
            //scores[4] = 50;

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(scores[i]);
            }

            // 5개짜리 배열을 만들었는데 6번째 데이터를 읽는 다면
            // 에러가 발생 outofrange에러 발생

            // 배열의 숫자 맞추는게 어렵다고 생각된다면
            for (int i = 0; i < scores.Length; i++)
            {
                Console.WriteLine(scores[i]);
            }

            // foreach
            foreach (int score in scores)
            {
                Console.WriteLine(score);
            }
        }
    }
}

🧩 배열이란?

  • 같은 타입의 데이터를 묶어서 저장하는 자료구조
  • 메모리에 연속적으로 배치
  • 각 데이터는 인덱스(번호)로 구분하고, 0부터 시작
  • new 키워드를 사용해 힙 메모리에 저장 (C# 배열은 무조건 힙에 존재)

🛠️ 배열 선언과 초기화

방법 1 - 선언하고 나중에 값 할당

int[] array = new int[5];  // 길이가 5인 정수 배열 선언
array[0] = 10;
array[1] = 20;
array[2] = 30;
array[3] = 40;
array[4] = 50;

방법 2 - 선언과 동시에 초기화

int[] array2 = new int[] { 10, 20, 30 };

방법 3 - 크기까지 명시하며 초기화

int[] array3 = new int[5] { 10, 20, 30, 40, 50 };

방법 4 - new 키워드 생략 가능

int[] array4 = { 10, 20, 30 };

⚠️ 배열은 크기 변경 불가

배열은 한번 크기를 정하면 이후 크기를 변경할 수 없습니다.
(크기를 유동적으로 관리하는 자료구조는 List<T>입니다.)


📍 배열은 참조 타입 (Call by Reference)

int[] scores = new int[5] { 10, 20, 30, 40, 50 };
int[] scores2 = scores;  // 같은 배열 메모리를 가리킴

scores2는 새로운 배열이 아니라, 기존 scores 배열의 주소를 복사해 참조하는 변수입니다.
즉, 하나의 배열을 두 변수가 공유하는 형태입니다.

scores2[0] = 9999;  // scores2에서 바꾸면 scores도 함께 변경

🌀 배열 순회 방법

1️⃣ for문 사용

for (int i = 0; i < scores.Length; i++)
{
    Console.WriteLine(scores[i]);
}

2️⃣ foreach문 사용 (권장)

foreach (int score in scores)
{
    Console.WriteLine(score);
}

foreach문은 배열 전체를 순회할 때 실수할 가능성이 적고, 가독성이 좋습니다.


💥 배열 범위 초과 시 예외 발생

for (int i = 0; i < 10; i++)  // 길이 5인데 10까지 반복 시도
{
    Console.WriteLine(scores[i]);  // IndexOutOfRangeException 발생
}

배열의 길이를 초과하는 인덱스로 접근하면 런타임 예외인
IndexOutOfRangeException이 발생합니다.


배열을 이용한 몬스터 관리

네임스페이스 & 클래스 정의

namespace CSharp_DataStructure
{
    class Player
    {
        // 플레이어 클래스 (아직 기능 없음)
    }

    class Monster
    {
        // 몬스터 클래스 (아직 기능 없음)
    }

    class Program
    {
        Player player;        // 플레이어 객체 선언
        Monster monster1;     // 몬스터1 선언
        Monster monster2;     // 몬스터2 선언
        Monster monster3;     // 몬스터3 선언

        static void Main(string[] args)
        {

배열 선언 및 초기화

int[] scores = new int[5] { 10, 20, 30, 40, 50 };
// 힙 메모리에 길이 5짜리 정수 배열 할당 후 초기화

int[] scores2 = scores;  
// scores2는 scores와 같은 배열을 가리킴 (Call by Reference)

배열 값 변경 (참조 특성 확인)

scores2[0] = 9999;  
// scores2[0]를 바꾸면 scores[0]도 같이 변경됨

배열 순회 (for문과 foreach문 비교)

for (int i = 0; i < scores.Length; i++)
{
    Console.WriteLine(scores[i]);
}
// 전통적 for문을 이용한 순회
foreach (int score in scores)
{
    Console.WriteLine(score);
}
// foreach문을 이용한 순회 (더 직관적)

범위 초과 시 예외 확인

// 아래 코드는 실행 시 예외 발생
// for (int i = 0; i < 10; i++)
// {
//     Console.WriteLine(scores[i]);  // IndexOutOfRangeException
// }

🔗 배열과 List의 차이점 정리

구분배열(Array)리스트(List)
메모리연속된 공간연속적일 수도, 아닐 수도 있음
크기고정가변
성능빠름비교적 느림
참조 특성Call by ReferenceCall by Reference
기능단순 데이터 저장다양한 메서드 제공 (Add, Remove 등)

profile
李家네_공부방

0개의 댓글