3월 17일 #배열

sejun-Lee·2025년 3월 17일

배열 (Array)

  • 동일한 자료형의 요소들로 구성된 데이터 집합
  • 인덱스를 통하여 배열요소(Element)에 접근할 수 있음
  • 배열의 처음 요소의 인덱스는 0부터 시작함

     string name1 = "김정택";
     string name2 = "김재성";
     string name3 = "용준헌";
     //75개
     string name4 = "강민혁";
     string name5 = "강소현";
     string name6 = "권봉근";

     string name;          // 문자열 하나 만들기
     string[] names;       //문자열 배열 만들기 : 문자열 여러개 만들기

     int value;           //정수 저장소 value로 하나 만들기
     value = 10;          //저장소에 10 저장하기

     int[] values;        // 정수 여러개 담을 수 있는 저장소 만들기
     values = new int[200];   //200개 짜리 저장소 만들기

✅< 배열의 기본 >

  • 배열을 만들기 위해 자료형과 크기를 정하여 생성
  • 배열의 요소에 접근하기 위해[인덱스]를 사용
  • 배열의 length 를 통해 크기를 확인

      자료형[] 배열이름 = new 자료형[크기];
     int[] scores = new int[5];  // 크기 5의 배열 선언
     // 배열을 크기가 정해져 있을때 쓰는게 국룰!!

     scores[0] = 10;
     scores[1] = 20;
     scores[2] = 30;
     scores[3] = 40;
     scores[4] = 50;

     //int score0 = 10;
     //int score1 = 20;
     //int score2 = 30;
     //int score3 = 40;
     //int score4 = 50;

     Console.WriteLine(scores[0]); //0번쨰 요소 불러오기
     Console.WriteLine(scores[1]); //0번쨰 요소 불러오기
     Console.WriteLine(scores[2]); //0번쨰 요소 불러오기
     Console.WriteLine(scores[3]); //0번쨰 요소 불러오기
     Console.WriteLine(scores[4]); //0번쨰 요소 불러오기

     Console.WriteLine("배열에 있는 int의 갯수는 : {0}", scores.Length);



     string[] shortCuts = new string[4];

     shortCuts[0] = "고급회복약";
     shortCuts[1] = "성스로운부적";
     shortCuts[2] = "아드로핀물약";
     shortCuts[3] = "파괴폭탄";

     int number = 1;

     Console.WriteLine("사용할 단축키를 1~4 사이로 골라주시기 바랍니다.");
     string input = Console.ReadLine();
     int choice = int.Parse(input);

     Console.WriteLine("{0} 아이템을 사용합니다", shortCuts[choice - 1]);



     for (int i = 0; i < shortCuts.Length; i++) // 4회 반복 -> length사용시 가지고 있는 갯수만큼만
     {
         Console.WriteLine("{0}번째 아이템이 {1} 입니다", i + 1, shortCuts[i]);
     }

foreach 반복문

  • 데이터집합의 처음부터 끝까지 반복

     foreach (string item in shortCuts)
     {
         Console.WriteLine("배열에 있는 아이템 : {0}", item);
     }

✅< 다차원 배열 >

  • 배열의 [] 괄호 안에 , 를 써서 표현

     string[,] shortCuts;
     shortCuts = new string[3, 4]
     {
         {"고급회복약","성스러운부적","만능물약","회오리수류탄" },
         {"고급회복약","진군의깃발","아드로핀물약","파괴폭탄" },
         {"정령의가호","성스러운부적","시간정지물약","암흑수류탄" }
     };

     for (int i = 0; i < shortCuts.GetLength(0); i++)
     {
         for (int j = 0; j < shortCuts.GetLength(1); j++)
         {
             Console.Write(shortCuts[i, j] + " ");
         }
         Console.WriteLine();
     }


     shortCuts = new string[3, 4];
     shortCuts[0, 0] = "포션";
     shortCuts[0, 1] = "폭탄";
     shortCuts[0, 2] = "섬광";
     shortCuts[0, 3] = "부적";

     shortCuts[1, 0] = "허수아비";
     shortCuts[1, 1] = "룬조각";
     shortCuts[1, 2] = "혈액팩";
     shortCuts[1, 3] = "돌덩이";

     shortCuts[2, 0] = "마나팩";
     shortCuts[2, 1] = "몬스터캡슐";
     shortCuts[2, 2] = "몬스터볼";
     shortCuts[2, 3] = "이상한사탕";

     for (int i = 0; i < shortCuts.GetLength(0); i++)
     {
         for (int j = 0; j < shortCuts.GetLength(1); j++)
         {
             Console.WriteLine("{0} 번쨰줄 {1} 번쨰 아이템 : {2}", i, j, shortCuts[i, j]);
         }
         Console.WriteLine();
     }
     Console.WriteLine("총 아이템의 갯수는 {0}", shortCuts.Length);

 static void arrTest(string[] strArr)
 {
     strArr[2] = "영원히 변하지 않길";
 }

 static void IntTest(ref int value)  // ref 레퍼런스 -> 바로가기, 원본을 준다
 {
     value = value + 10;
 }

 static void ArrayTest(int[] array)  // ref 레퍼런스 -> 바로가기, 원본을 준다
 {
     array[2] = 999;
 }


 static void Main(string[] args)
 {
     //string은 예외적으로 배열이나 원본이 바뀌지 않음.
     string[] myArr = new string[] { "에이스", "비스", "씨스", "디스" };
     Console.WriteLine(myArr);   // 배열은 참조타입으로 바로가기 주소를 가지고 있을 뿐임. 출력 X
     arrTest(myArr);
     Console.WriteLine(myArr[0]);	// 에이스


     int test = 5;
     Console.WriteLine("함수 전 값 : {0}", test);	// 5
     IntTest(ref test);  // ref 레퍼런스 -> 바로가기 원본을 보내서 바꾸기 때문에 원본이 바뀐다
     Console.WriteLine("함수 전 값 : {0}", test);	// 15

     // 배열은 ref 쓸 필요 없음. 애초에 바로가기로 구현되어 있음.
     int[] arry = { 1, 2, 3, 4 };
     Console.WriteLine("함수 전 값 : {0}", arry[2]);	// 3
     ArrayTest(arry);
     Console.WriteLine("함수 전 값 : {0}", arry[2]);	// 999
}

     			  //01234
     string text = "abcde";      // string은 char 처럼 한글자만 바꾸는 건 불가능.
     char[] array = text.ToCharArray();  // string 을 char 배열로 변환해서 한글자씩 저장


     array[0] = char.ToUpper(array[0]);  // 0번째 글자만 대문자로 바꿔라

     text = new string(array);   // 0번째 글자를대문자로 바꾼후 text에 다시 저장
     Console.WriteLine(text);    // 출력

     Console.WriteLine(text[2]); // text 2번째 글자 출력

     for (int i = 0; i < text.Length; i++)
     {
         Console.WriteLine(text[i]);     // text 글자 한자리씩 출력
     }

     array[2] = 'X';             // 2번째 글자를 X로 바꿈

     for (int i = 0; i < array.Length; i++)
     {
         Console.WriteLine(array[i]);    // array에 한글자씩 배열로 저장한것 출력
     }

     Console.WriteLine(text.ToUpper());  // abcde 대문자로 변환
     Console.WriteLine(text.ToLower());  // abcde 소문자로 변환

     string text = "나는 점심이 너무 맛있었다";
     string[] words = text.Split(' ');   // 띄어쓰기로 나누기
     Console.WriteLine(words[1]);	// 점심이

     int[] array = new int[5] { 1, 2, 3, 4, 5 };     //간단한 배열 셋팅
     int[] array1 = { 1, 2, 3, 4, 5, 6 };     // 배열 크기를 지정하지 않고 간단히 쓰는 방법
     int[,] array2 =
     {
         {1,2,3 },
         {4,5,6 },
         {7,8,9 }
     };


     string[,] students = new string[8, 30];
     students[1, 12] = "김전사";
     students[2, 29] = "이궁수";
     students[7, 1] = "박도적";
     Console.WriteLine(students.Length);     // 8*30 = 240개

     string shortCuts1 = "고급회복약";
     string shortCuts2 = "성스로운부적";
     string shortCuts3 = "아드로핀물약";
     string shortCuts4 = "파괴폭탄";

     Console.WriteLine("사용할 단축키를 1~4 사이로 골라주시기 바랍니다.");
     string input = Console.ReadLine();
     int choice = int.Parse(input);

     switch (choice)
     {
         case 1:
             Console.WriteLine("{0} 아이템 사용", shortCuts1);
             break;
         case 2:
             Console.WriteLine("{0} 아이템 사용", shortCuts2);
             break;
         case 3:
             Console.WriteLine("{0} 아이템 사용", shortCuts3);
             break;
         case 4:
             Console.WriteLine("{0} 아이템 사용", shortCuts4);
             break;
     }
profile
초보 개발자

0개의 댓글