C# 문법 종합반 2주차 강의 시작~,,
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 입니다.
중첩 조건문 : 하나의 조건문 안에 또 다른 조건문이 포함된 형태의 조건문
변수나 식의 결과에 따라 다른 코드 블록을 실행
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;
}
}
(조건식) ? 참일 경우의 값 : 거짓일 경우의 값;
for (초기식; 조건식; 증감식)
{
// 조건식이 참일 경우 실행
}
foreach (자료형 변수 in 배열 또는 컬렉션)
{
// 배열 또는 컬렉션의 모든 요소에 대해 반복적으로 실행
}
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();
}
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차원 배열
데이터_유형[] 배열_이름;
배열_이름 = 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();
}
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<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);
}
후입선출(LIFO) 구조의 자료구조
Stack<int> stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
int value = stack.Pop(); // value = 2
선입선출(FIFO) 구조의 자료구조
Queue<int> queue = new Queue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
int value = queue.Dequeue(); // value = 1;
중복되지 않은 요소들로 이루어진 집합
HashSet<int> set = new HashSet<int>();
set.Add(1);
set.Add(1);
foreach(int element in set)
{
Console.WriteLine(element);
}
1
[접근 제한자] [리턴 타입] [메서드 이름] ([매개변수])
{
// 메서드 실행 코드
}
[메서드 이름]([전달할 매개변수]);
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
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
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();
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;
}