⚔ for문
for (int i = 1; i <= 100; i++)
{
if (i % 2 != 0)
{
Console.WriteLine(i);
}
}
⚔ while문
int i = 1;
while (i <= 100)
{
if (i % 2 != 0)
{
Console.WriteLine(i);
}
i++;
}
⚔ do-while문
int i = 1;
do
{
if (i % 2 != 0)
{
Console.WriteLine(i);
}
i++;
}
while (i <= 100);
⚔ 배열 원소의 합계 & 평균
int sum = 0;
float average = 0f;
int[] a = { 10, 20, 30, 40, 50 };
for (int i = 0; i < a.Length; i++)
{
sum += a[i];
}
average = sum / a.Length;
Console.WriteLine($"Sum: {sum}");
Console.WriteLine("Average: {0}",average);
⚔ 팩토리얼
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
int f = 1;
for (int i = 1; i <= n; i++)
{
f *= i;
}
Console.WriteLine($"Factorial of {n} is {f}");
⚔ 숫자 맞추기
// Random 클래스를 사용할 때 객체 생성 먼저!
Random random = new Random();
int ans = random.Next(1, 101);
while (true)
{
Console.Write("Enter your guess (1-100): ");
int n = int.Parse(Console.ReadLine());
if (n == ans)
{
Console.WriteLine("Congratulations! You guessed the number.");
break;
}
else if (n < ans)
{
Console.WriteLine("Too low! Try again.");
}
else
{
Console.WriteLine("Too high! Try again.");
}
}
숫자 앞에 0을 채울 때는 {i*j:D2}와 같이 :D2를 추가해 주면 된다. (D2의 2는 자릿수)
숫자 앞에 공백을 채울 때는 {i*j,2}와 같이 ,2를 추가해 주면 된다. (,2의 2는 자릿수)
⚔ 구구단 출력(세로)
for (int i = 1; i <= 9; i++)
{
for (int j = 2; j <= 9; j++)
{
Console.Write($"{j} x {i} = {i*j,2} ");
}
Console.WriteLine();
}
⚔ 구구단 출력(가로)
for (int i = 2; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
Console.Write($"{i} x {j} = {i*j,2} ");
}
Console.WriteLine();
}
⚔ 배열의 최대값 & 최소값
int[] a = { 10, 20, 30, 40, 50 };
int min = a[0];
int max = a[0];
for (int i = 1; i < a.Length; i++)
{
if (a[i] > max) max = a[i];
if (a[i] < min) min = a[i];
}
Console.WriteLine($"max: {max}, min: {min}");
행맨 게임 이전 코드는 문제를 잘못 이해해서 문자열을 입력받아서 비교했다..
⚔ 행맨 게임(이전)
// ToCharArray(): 문자열을 char 배열로 변환
// new string(char 배열): char 배열을 문자열로 변환
char[] secretWord = "hangman".ToCharArray();
char[] guessWord = "_______".ToCharArray();
int attempts = 6;
bool wordGuessed = false;
while (attempts>0 && !wordGuessed)
{
Console.Write($"(남은 기회:{attempts}) \"{new string(guessWord)}\"를 예측해 주세요: ");
string s = Console.ReadLine();
if (s.Length != secretWord.Length)
{
Console.WriteLine("문자열의 길이가 맞지 않습니다. 다시 입력해주세요.");
continue;
}
attempts--;
wordGuessed = true;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == secretWord[i]) guessWord[i] = s[i];
else wordGuessed = false;
}
}
if (wordGuessed) Console.WriteLine("성공하셨습니다!");
else Console.WriteLine("실패하셨습니다.");
팀플을 하면서 문제가 있는 걸 확인하고 수정한 코드이다.
⚔ 행맨 게임(수정)
using System;
using System.Collections.Generic;
namespace HangmanGame
{
class Program
{
static void Main(string[] args)
{
// 맞춰야 할 정답
string secretWord = "hangman";
// 사용자가 맞추어야 할 글자 상태
char[] guessWord = new char[secretWord.Length];
for (int i = 0; i < guessWord.Length; i++)
{
guessWord[i] = '_';
}
// 시도 가능 횟수
int attempts = 6;
// 맞춘 글자를 저장할 자료구조 (중복 추측 방지)
HashSet<char> guessedChars = new HashSet<char>();
bool wordGuessed = false;
while (attempts > 0 && !wordGuessed)
{
// 화면 지우고 현 상태 출력
Console.Clear();
DrawHangman(6 - attempts);
Console.WriteLine("현재 단어: " + new string(guessWord));
Console.WriteLine($"남은 시도 횟수: {attempts}");
Console.Write("추측할 글자를 입력하세요: ");
string input = Console.ReadLine();
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("입력이 비어 있습니다. 다시 시도해주세요.");
Console.WriteLine("계속하려면 아무 키나 누르세요...");
Console.ReadKey();
continue;
}
// 여러 글자를 입력한 경우 첫 글자만 사용
char guessedChar = input[0];
// 이미 추측했던 글자인지 확인
if (guessedChars.Contains(guessedChar))
{
Console.WriteLine($"'{guessedChar}' 문자는 이미 추측하셨습니다. 다시 시도하세요.");
Console.WriteLine("계속하려면 아무 키나 누르세요...");
Console.ReadKey();
continue;
}
// 추측 문자 추가
guessedChars.Add(guessedChar);
// 단어 내에 guessedChar가 있는지 확인해서 맞는 자리를 업데이트
bool correctGuess = false;
for (int i = 0; i < secretWord.Length; i++)
{
if (secretWord[i] == guessedChar)
{
guessWord[i] = guessedChar;
correctGuess = true;
}
}
// 맞춘 글자가 없으면 attempts 감소
if (!correctGuess)
{
attempts--;
Console.WriteLine($"틀렸습니다! '{guessedChar}'는 단어에 없습니다.");
}
else
{
Console.WriteLine($"맞았습니다! '{guessedChar}'는 단어에 포함되어 있습니다.");
}
// 단어를 모두 맞췄는지 확인
if (secretWord == new string(guessWord))
{
wordGuessed = true;
}
Console.WriteLine("계속하려면 아무 키나 누르세요...");
Console.ReadKey();
}
// 게임 종료 후 결과 확인
Console.Clear();
if (wordGuessed)
{
Console.WriteLine($"축하합니다! 정답은 '{new string(guessWord)}' 입니다.");
}
else
{
DrawHangman(6); // 최종 하강(?)된 행맨 출력
Console.WriteLine($"실패했습니다! 정답은 '{secretWord}' 였습니다.");
}
}
/// <summary>
/// 틀린 횟수에 따라 행맨 그림을 출력하는 메서드
/// wrongGuessCount 범위는 0 ~ 6 (0 = 하나도 안 틀림, 6 = 완전히 그림 완성)
/// </summary>
/// <param name="wrongGuessCount"></param>
static void DrawHangman(int wrongGuessCount)
{
string[] hangmanPics =
{
// wrongGuessCount = 0 (틀린 게 없음)
@"
+---+
| |
|
|
|
|
=========",
// 1번 틀림
@"
+---+
| |
O |
|
|
|
=========",
// 2번 틀림
@"
+---+
| |
O |
| |
|
|
=========",
// 3번 틀림
@"
+---+
| |
O |
/| |
|
|
=========",
// 4번 틀림
@"
+---+
| |
O |
/|\ |
|
|
=========",
// 5번 틀림
@"
+---+
| |
O |
/|\ |
/ |
|
=========",
// 6번 틀림 (완전히 그림 완성)
@"
+---+
| |
O |
/|\ |
/ \ |
|
========="
};
// 범위 체크
if (wrongGuessCount < 0) wrongGuessCount = 0;
if (wrongGuessCount > 6) wrongGuessCount = 6;
Console.WriteLine(hangmanPics[wrongGuessCount]);
}
}
}
Convert.ToInt32('1');는 1의 ASCII 코드 값을 반환한다.
char -> int로 변경할 때는 char a='1'; int n = a - '0';와 같이 - '0'을 해준다.
숫자 야구 게임 처럼 반복이 되지 않는 값을 뽑을 때 이전 코드에서는
⚔ 숫자 뽑기(이전)
while (true)
{
int a = random.Next(0, 10);
int b = random.Next(0, 10);
int c = random.Next(0, 10);
if (a != b && a != c && b != c)
{
// 초기화할 때 new int[3]없이 사용 불가 --> new 없이 초기화 하려면 선언과 동시에 초기화 해야 함!
targetNumber = new int[3]{a,b,c};
break;
}
}
처럼 값이 다 다를 때까지 loop를 계속 돌아서 뽑는 방식을 사용했다. 팀원의 코드 중에서 List를 이용해서 랜덤으로 뽑고 뽑은 값은 Remove하는 방식을 보고 loop를 딱 3번만 돌아서 비용이 훨씬 적겠다는 생각이 들어서 코드를 아래와 같이 수정했다.
⚔ 숫자 야구
int[] targetNumber= new int[3];
int[] userGuess = new int[3];
int strikes;
int balls;
bool guessedCorrectly = false;
Random random = new Random();
/* 이전 방식
while (true)
{
int a = random.Next(0, 10);
int b = random.Next(0, 10);
int c = random.Next(0, 10);
if (a != b && a != c && b != c)
{
// 초기화할 때 new int[3]없이 사용 불가 --> new 없이 초기화 하려면 선언과 동시에 초기화 해야 함!
targetNumber = new int[3]{a,b,c};
break;
}
}
*/
// List를 활용한 방식
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (int i = 0; i < 3; i++)
{
// (0 ~ Count-1) 범위의 index를 뽑기
int index = random.Next(0, list.Count);
// 해당 인덱스의 값을 저장하고
targetNumber[i] = list[index];
// 해당 인덱스의 값을 List에서 Remove
list.RemoveAt(index);
}
int attempts = 0;
while (!guessedCorrectly)
{
strikes = 0;
balls = 0;
Console.Write("Enter your guess (3 digits): ");
string s = Console.ReadLine();
if (s.Length != 3)
{
Console.WriteLine("잘못 입력하셨습니다.");
continue;
}
attempts++;
guessedCorrectly = true;
for (int i = 0; i < 3; i++)
{
//userGuess[i] = Convert.ToInt32(s[i]); -- ASCII 코드 값을 반환함
userGuess[i] = s[i] - '0';
if (targetNumber[i] == userGuess[i]) strikes++;
else
{
guessedCorrectly = false;
for (int j = 0; j < 3; j++)
{
if (targetNumber[j] == userGuess[i]) balls++;
}
}
}
Console.WriteLine($"{strikes} Strike(s), {balls} Ball(s)");
}
Console.WriteLine($"Congratulations! You've guessed the number in {attempts} attempts.");