본문 바로가기

c# ☃️

[C#] 배열(Array) - 정의/기본 예제/사용법

배열(Array)이란 ?

🫥 Stores a fixed sized sequential collection of elements
🫥 Only of the same type
🫥 All kinds of types : int string object etc
🫥 Great to store a collection of data - easier to think of a collection of variables of the same type stored at contiguous memory locations.
🫥 뭔가를 저장하려면 특정 인덱스에 저장


배열 선언방법(Declaring an array)

🫥 dateType[] arrayName = new dataType[amountOfEntries];

배열 지정방법(Assigning values to an array)
🫥 ArrayName[index] = value;


사용예제

namespace ArrayEx;
class Program
{
    static void Main(string[] args)
    {
        //첫번째 방법 - 배열에 값 할당 
        int[] grades = new int[5];

        grades[0] = 60;
        grades[1] = 70;
        grades[2] = 80;
        grades[3] = 90;
        grades[4] = 100;

        for(int i = 0; i < grades.Length; i++)
        {
            Console.WriteLine("grades[{0}] : {1}",i, grades[i]);
        }


        // 두번째 방법 - 배열에 값 할당
        int[] gradesSecond = { 60, 70, 80, 90, 100 };

        Console.WriteLine("gradesSecond 길이 : {0}", gradesSecond.Length);

        // 세번째 방법 - 배열에 값 할당
        int[] gradesThird = new int[] { 60, 70, 80, 90, 100 };

    }
}


실행결과