Unity 내일배움캠프 TIL 0814 (2) | C# 기초 | 조건문과 반복문 | 배열과 컬렉션 | 메서드와 구조체

cheeseonrose·2023년 8월 14일
0

Unity 내일배움캠프

목록 보기
7/89
post-thumbnail

C# 문법 종합반 2주차 강의 시작~,,

조건문과 반복문

if, else if, else

  • if : 조건식의 결과에 따라 실행 여부를 결정

    • 중괄호는 웬만하면 사용할 것
  • else : if문에서 조건식이 거짓일 경우 실행

  • else if : if문의 조건식이 거짓일 때, 새로운 조건식을 사용하여 실행 여부를 결정

     static void Main(string[] args)
      {       
     	int playerScore = 100;
      	string playerRank = "";
    
    	if (playerScore >= 90)
      	{
      		playerRank = "Diamond";
       	} else if (playerScore >= 80)
        {
        	playerRank = "Platinum";
        } else if (playerScore >= 70)
        {
        	playerRank = "Gold";
        } else if (playerScore >= 60)
        {
        	playerRank = "Silver";
        } else {
        	playerRank = "Bronze";
        }
    
    	Console.WriteLine("플레이어의 등급은 {0} 입니다.", playerRank);
      }
    플레이어의 등급은 Diamond 입니다.
  • 중첩 조건문 : 하나의 조건문 안에 또 다른 조건문이 포함된 형태의 조건문

switch

  • 변수나 식의 결과에 따라 다른 코드 블록을 실행

    static void Main(string[] args)
     {  
     	Console.WriteLine("1: 전사 / 2: 마법사 / 3: 궁수 ");
      	string job = Console.ReadLine();
    
    	switch (job)
      	{
      		case "1" :
              	Console.WriteLine("전사를 선택하셨습니다.");
                break;
            case "2" :
            	Console.WriteLine("마법사를 선택하셨습니다.");
              	break;
            default:
            	Console.WriteLine("궁수를 선택하셨습니다.");
              break;
     	}
    }

3항 연산자

  • 조건식의 결과에 따라 두 값을 선택하는 연산자
    (조건식) ? 참일 경우의 값 : 거짓일 경우의 값;

for

  • 초기식, 조건식, 증감식을 사용한 반복문
    for (초기식; 조건식; 증감식)
     {
    	// 조건식이 참일 경우 실행
     }
  • foreach : 배열이나 컬렉션에 대한 반복문을 작성할 때 사용
    foreach (자료형 변수 in 배열 또는 컬렉션)
     {
    	// 배열 또는 컬렉션의 모든 요소에 대해 반복적으로 실행
     }

while

  • 조건식이 참(true)인 동안 코드 블록을 반복
    while (조건식)
     {
    	// 조건식이 참일 경우 실행
     }
    • for과 while 비교
      • for 문은 반복 횟수를 직관적으로 알 수 있음 -> 가독성이 좋음
      • while문은 반복 조건에 따라 조건문의 실행 횟수가 유동적 -> 코드가 더 간결해질 수도 있음
  • do while : 조건식을 검사하기 전 코드 블록을 먼저 한 번 실행
    do
     { 
     	// 조건식이 참일 경우 실행
     }
     while (조건식);

중첩반복문

for (int i = 0; i < 5; i++)
{
	for (int j = 0; j < 3; j++) 
    {
    	...
    }
}
  • 구구단 출력

    for (int i = 1; i <= 9; i++)
     {
     	for (int j = 2; j <= 9; j++)
      	{
          	Console.Write(j + " x " + i + " = " + (i * j) + "\t");
        }
        Console.WriteLine();
     }

break와 continue

  • break : 반복문을 중지
  • continue : 현재 반복을 중지하고 다음 반복을 실행
for (int i = 1; i <= 10; i++)
{
	if (i %3 == 0)
    {
    	continue;
    }
    
    Console.WriteLine(i);
    
    if (i == 7)
    {
    	break;
    }
}
1
2
4
5
7

배열과 컬렉션

배열

  • 동일한 자료형의 값들이 연속적으로 저장되는 자료 구조

  • 1차원 배열

    • 동일한 데이터 유형을 가지는 데이터 요소들을 한 번에 모아서 다룰 수 있음
    • 인덱스를 사용하여 요소에 접근
    • 선언된 크기만큼 메모리에 공간을 할당받음
    • 배열_이름.Length : 배열의 길이
    데이터_유형[] 배열_이름;
    
     배열_이름 = new 데이터_유형[크기];
  • 다차원 배열

    • 여러 개의 배열을 하나로 묶어놓음
    • 행과 열로 이루어짐
      int[,] array = new int[2, 3];
        
      array[0, 0] = 1;
      array[0, 1] = 2;
      ...
      int[,] map = new int[5, 5]
       {
       	{1, 1, 0, 1, 1 },
        	{1, 0, 1, 0, 0 },
        {1, 1, 0, 1, 1 },
        {0, 1, 1, 1, 0 },
        {1, 0, 1, 0, 1 },
       };
       
       for (int i = 0; i < 5; i++)
       {
       	for (int j = 0; j < 5; j++)
        	{
            if (map[i,j] == 1)
            {
            	Console.Write("■");
            } else
            {
            	Console.Write("□");
            }
        }
        Console.WriteLine();
      }

컬렉션

  • 자료를 모아 놓은 데이터 구조
  • 크기가 가변적
  • System.Collections.Generic 네임스페이스 추가
  • List
    • 가변적인 크기를 갖는 배열
      List<int> numbers = new List<int>();
       numbers.Add(1);
       numbers.Add(2);
       // numbers[0] 처럼 인덱스 접근 가능
       
       foreach(int number in numbers)
       {
       	Console.Write(number);
       }
      1
       2
  • Dictionary
    • 키와 값으로 구성된 데이터 저장
    • 중복된 키를 가질 수 없음
      Dictionary<string, int> scores = new Dictionary<string, int>();
       scores.Add("potato", 100);
       scores.Add("tomato", 80);
       
       foreach(KeyValuePair<string, int> pair in scores)
       {
       	Console.WriteLine(pair.Key + " : " + pair.Value);
       }
  • Stack
    • 후입선출(LIFO) 구조의 자료구조

      Stack<int> stack = new Stack<int>();
      
       stack.Push(1);
       stack.Push(2);
       
       int value = stack.Pop();	// value = 2 
  • Queue
    • 선입선출(FIFO) 구조의 자료구조

      Queue<int> queue = new Queue<int>();
      
       queue.Enqueue(1);
       queue.Enqueue(2);
       
       int value = queue.Dequeue();	// value = 1;
  • HashSet
    • 중복되지 않은 요소들로 이루어진 집합

      HashSet<int> set = new HashSet<int>();
      
       set.Add(1);
       set.Add(1);
       
       foreach(int element in set)
       {
       	Console.WriteLine(element);
       }
      1

배열과 리스트

  • 메모리 사용량 증가 : 리스트는 동적으로 크기를 할당하기 때문에 배열보다 많은 메모리를 사용
  • 데이터 접근 시간 증가 : 리스트는 연결 리스트로 구현되므로, 배열에 비해 데이터 접근 시간이 느림
  • 코드 복잡도 증가 : 리스트는 데이터 추가, 삭제 등의 작업이 배열보다 간편하지만, 코드의 가독성과 유지보수성이 저하될 수 있음
    -> 적재적소에 사용하는 것이 중요

메서드와 구조체

메서드

  • 특정 작업을 수행하기 위해 사용되는 독립적 기능 단위
  • 코드의 재사용성과 모듈화를 위해 사용
  • 가독성과 유지보수성이 좋아짐
  • 코드의 중복 제거
  • 메서드를 통해 단위 작업을 추상화 가능
  • 메서드 선언 방법
    • 접근 제한자 : public, private, protected
    • 반환값 : 없을 경우 void
    [접근 제한자] [리턴 타입] [메서드 이름] ([매개변수])
     {
     	// 메서드 실행 코드
     }
  • 메서드 호출 방법
    [메서드 이름]([전달할 매개변수]);
    void PrintFullName(string firstName, string lastName)
     {
     	Console.WriteLine("Full Name: " + firstName + " " + lastName);
     }
     
     PrintFullName("Potato", "Tomato");
  • 메서드 오버로딩
    • 동일한 이름의 메서드를 다양한 매개변수 목록으로 다중 정의하는 개념
    • 메서드 호출시 매개변수의 형태에 따라 적절한 메서드가 선택되도록 함 (반환값이 달라도 동일한 메서드로 취급함)
    • 기능이나 작업은 동일하지만 입력값에 따라 다르게 동작해야 할 때 사용
    void PrintMessage(string message)
     {
     	Console.WriteLine("Message: " + message);
     }
     
     void PrintMessage(int number)
     {
     	Console.WriteLine("Number: " + number);
     }
     
     PrintMessage("Hello, World!");
     PrintMessage(10);
    Hello, World!
     10

재귀호출

  • 메서드가 자기 자신을 호출하는 것
  • 문제를 작은 부분으로 분할하여 해결하는 방법 중 하나
  • 호출 스택에 호출된 메서드의 정보를 순차적으로 쌓고, 메서드가 반환되면서 스택에서 순차적으로 제거되는 방식으로 동작
  • 무한루프를 돌지 않게 주의해야 함 -> StackOverflow 발생
static void CountDown(int n)
{
	if (n <= 0)
    {
    	Console.WriteLine("Done");
    } else 
    {
    	Console.WriteLine(n);
    	CountDown(n-1);
    }
}

static void Main(string[] args)
{
	CountDown(5);
}
5
4
3
2
1
Done

구조체

  • 여러 개의 데이터를 묶어서 하나의 사용자 정의 형식으로 만들기 위한 방법
  • 값 형식(Value Type)으로 분류되며, 데이터를 저장하고 필요한 기능 제공
  • struct를 사용하여 선언
  • 멤버 변수(필드)와 멤버 함수(메서드)로 구성
struct Person
{
	public string Name;
    public int Age;
    
    public void PrintInfo()
    {
    	Console.WriteLine($"Name: {Name}, Age: {Age}");
    }
}
Person person;
person.Name = "potato";
person.Age = 100;
person.PrintInfo();

2주차 과제

숫자 맞히기 게임

 static void Main(string[] args)
 {
 	int targetNumber = new Random().Next(1, 101);
  	int playerNum = 0;
    Console.WriteLine("1부터 100 사이의 숫자를 맞혀보세요!");
    while (playerNum != targetNumber)
    {
    	Console.Write("숫자를 입력하세요: ");
      	playerNum = int.Parse(Console.ReadLine());
        if (playerNum < targetNumber)
        {
        	Console.WriteLine("더 큰 숫자입니다.");
        }
        else if (playerNum > targetNumber)
        {
         	Console.WriteLine("더 작은 숫자입니다.");
        }
        else
        {
        	Console.WriteLine("정답입니다!");
        }
    }

	Console.WriteLine("1부터 9 사이의 숫자 3가지를 맞혀보세요!");

	int[] targetNumbers = new int[3];
  	for (int i = 0; i < targetNumbers.Length; i++)
    {
    	targetNumbers[i] = new Random().Next(1, 10);
    }

	while (true)
    {
    	Console.Write("숫자 3개를 입력하세요: ");
        string[] answer = Console.ReadLine().Split(' ');
        int[] playerNums = new int[3];
        for (int i = 0; i < playerNums.Length; i++)
        {
        	playerNums[i] = int.Parse(answer[i]);
        }

		int correct = 0;
      	for (int i = 0; i < targetNumbers.Length; i++)
         {
         	for (int j = 0; j < playerNums.Length; j++)
          	{
              	if (targetNumbers[i] == playerNums[j])
                {
                	correct++;
                  	break;
                 }
             }
          }

		if (correct == 3)
        {
        	Console.WriteLine("정답입니다!");
          	break;
         }
         else
         {
              Console.WriteLine("{0}개 맞혔습니다.", correct);
          }
    }
 }

틱택토 게임

static void Main(string[] args)
 {
 	int[,] board = new int[3, 3];

	int gameOver = 0;
  	while (gameOver == 0)
  	{
      	Console.Write("Player1 : ");
        string[] player1Choice = Console.ReadLine().Split(',');
        int player1_x = int.Parse(player1Choice[0]);
        int player1_y = int.Parse(player1Choice[1]);
        board[player1_x, player1_y] = 1;

		Console.Write("Player2 : ");
      	string[] player2Choice = Console.ReadLine().Split(',');
        int player2_x = int.Parse(player2Choice[0]);
        int player2_y = int.Parse(player2Choice[1]);
        board[player2_x, player2_y] = 2;

		printGameBoard(board);

		gameOver = isGameOver(board);
      	if (gameOver == 1)
        {
        	Console.WriteLine("Player1 승리!");
         }
         else if (gameOver == 2)
         {
         	Console.WriteLine("Player2 승리!");
          }
     }
 }

 static void printGameBoard(int[,] gameBoard)
 {
 	for (int i = 0; i < gameBoard.GetLength(0); i++)
  	{
      	for (int j = 0; j < gameBoard.GetLength(1); j++)
        {
        	if (gameBoard[i, j] == 1)
          	{
              	Console.Write("O");
             } else if (gameBoard[i, j] == 2)
             {
             	Console.Write("X");
             } else
             {
             	Console.Write(".");
             }
             Console.Write(' ');
         }
         Console.WriteLine();
     }
 }

 static int isGameOver(int[,] gameBoard)
 {
 	for (int i = 0; i < gameBoard.GetLength(0); i++)
    {
    	int correct = 0;
      	int cur = gameBoard[i, 0];
        for (int j = 1; j < gameBoard.GetLength(1); j++)
        {
        	if (gameBoard[i,j] == cur)
            {
          		correct++;
            } else
            {
            	break;
            }
         }
         if (correct == 2)
         {
         	return cur;
         }
    }

	for (int i = 0; i < gameBoard.GetLength(0); i++)
  	{
      int correct = 0;
      int cur = gameBoard[0, i];
      for (int j = 1; j < gameBoard.GetLength(1); j++)
      {
      		if (gameBoard[j, i] == cur)
        	{
        		correct++;
        	}
        	else
        	{
        		break;
        	}
      }
      if (correct == 2)
      {
      	return cur;
      }
   }

	if (
  		(gameBoard[0, 0] == gameBoard[1, 1]) && (gameBoard[0, 0] == gameBoard[2, 2]) ||
        (gameBoard[2, 0] == gameBoard[1, 1]) && (gameBoard[2, 0] == gameBoard[0, 2])
    ) return gameBoard[1, 1];

	return 0;
 }

0개의 댓글