본문 바로가기

250611_C# 기초 학습 #2

@코야딩구2025. 6. 11. 14:11

5. 대한민국의 수도는?

코드:

// 1.퀴즈를 내서 정답을 맞추는 프로그램 작성해주세요. 
while (true)
{
    Console.WriteLine("Q. 대한민국의 수도는 어디인가요?" + '\n' + "1.인천   2.평창   3.서울   4.부산");
    Console.Write("정답: ");
    string s_in = Console.ReadLine();
    int num;
    if (int.TryParse(s_in, out num))
    {
        switch(num)
        {
            case 3:
                Console.WriteLine("정답입니다!");
                break;
            case 1:
            case 2:
            case 4:
                Console.WriteLine("오답입니다!");
                break;
            default:
                Console.WriteLine("1~4의 숫자를 입력해주세요.");
                break;
        }
    }
    else
    {
        Console.WriteLine("숫자가 아닙니다.");
    }
    Thread.Sleep(1000);
    Console.Clear();
}

영상:


6. 여행을 떠나요

코드:

while (true)
{
    Console.WriteLine("어디로 여행을 가고 싶나요?" + '\n' + "1.제주도   2.코타키나발루   3.싱가포르   4.태국");
    Console.Write("선택: ");
    string s_in = Console.ReadLine();
    int num;
    if (int.TryParse(s_in, out num))
    {
        switch (num)
        {
            case 1:
                Console.WriteLine("제주도는 한국의 섬으로 비교적 방문이 쉽고 다양한 놀거리/먹거리가 준비되어 있습니다.");
                break;
            case 2:
                Console.WriteLine("코타키나발루는 말레이시아 사바주의 주도로, 말레이시아 동부 보르네오섬 최대의 도시입니다.");
                break;
            case 3:
                Console.WriteLine("싱가포르는 동남아시아, 말레이 반도의 끝에 위치한 섬나라이자 항구 도시로 이루어진 도시 국가입니다.");
                break;
            case 4:
                Console.WriteLine("태국은 중국문화, 말레이문화, 불교문화, 힌두문화, 이슬람 문화가 혼재되어 있습니다." + '\n' + 
"불교적인 모습을 많이 띄지만, 문화 자체는 색다르고 스펙트럼이 넓은 형태를 띄고 있어요.");
                break;
            default:
                Console.WriteLine("1~4의 숫자를 입력해주세요.");
                break;
        }
    }
    else
    {
        Console.WriteLine("숫자가 아닙니다.");
    }
    Thread.Sleep(1000);
    Console.Clear();
}

영상:


7. 이름 찾기!

코드:

// 1. 이름 입력하기
while (true)
{
    Console.WriteLine("이름을 입력해주세요. (3~10글자)");
    Console.Write("이름: ");
    string s_in = Console.ReadLine();
    if (s_in.Length >= 3 && s_in.Length <= 10)
    {
        Console.WriteLine("안녕하세요! 제 이름은 " + s_in + " 입니다.");
    }
    else
    {
        Console.WriteLine("이름을 확인해주세요.");
    }
    Thread.Sleep(1000);
    Console.Clear();
}

영상:

코드:

// 2. 조건에 맞을때 까지 이름 입력
bool isFin = false;
while (!isFin)
{
    Console.WriteLine("이름을 입력해주세요. (3~10글자)");
    Console.Write("이름: ");
    string s_in = Console.ReadLine();
    if (s_in.Length >= 3 && s_in.Length <= 10)
    {
        Console.WriteLine("안녕하세요! 제 이름은 " + s_in + " 입니다.");
        isFin = true;
    }
    else
    {
        Console.WriteLine("이름을 확인해주세요.");
        Thread.Sleep(1000);
        Console.Clear();
    }
}

 

영상:


R1. 홀수 출력

// 1. 홀수 출력
// for문
Console.Write("for문: ");
for (int i = 1; i <= 100; i++)
{
    if (i % 2 == 1)
    {
        Console.Write(i + " ");
    }
}
Console.WriteLine("");

// while문
int num1 = 0;
Console.Write("while문: ");
while (++num1 <= 100)
{
    if (num1 % 2 == 1)
    {
        Console.Write(num1 + " ");
    }
}
Console.WriteLine("");

// do-while문
int num2 = 0;
Console.Write("do-while문: ");
do
{
    if (++num2 % 2 == 1)
    {
        Console.Write(num2 + " ");
    }
} while (num2 < 100); // 범위 while과 다름
// for문: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
// while문: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
// do-while문: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

R2. 배열을 사용한 합계 및 평균 계산

int[] a = new int[10];
for (int i = 0; i < a.Length; i++)
{
    a[i] = i * 10 + i;
    Console.Write(a[i] + " ");
}
Console.WriteLine();
int sum = 0;
for (int i = 0; i < 10; i++)
{
    sum += a[i];
}
Console.WriteLine("Sum: " + sum);
Console.WriteLine("Average: " + sum / 10.0f);
// Array: 0 11 22 33 44 55 66 77 88 99
// Sum: 495
// Average: 49.5

R3. 팩토리얼 계산

Console.Write("Enter a number: ");
string s_in = Console.ReadLine();
uint num;
ulong ret = 1;
if (uint.TryParse(s_in, out num))
{
    for (uint i = num; i > 0; i--)
    {
        ret *= i;
    }
}
Console.WriteLine("Factorial of 5 is " + ret);
// Enter a number: 15
// Factorial of 5 is 1307674368000

R4. 숫자 맞추기 게임

Random rand = new Random();
int q_num = rand.Next(1, 101);
bool isFin = false;
while (!isFin)
{
    Console.Write("Enter your guess (1-100): ");
    string s_in = Console.ReadLine();
    int a_num;
    if (int.TryParse(s_in, out a_num))
    {
        if (a_num == q_num)
        {
            Console.WriteLine("Congratulations! You guessed the number.");
            isFin = true;
        }
        else if (a_num > q_num)
        {
            Console.WriteLine("Too high! Try again.");
        }
        else
        {
            Console.WriteLine("Too low! Try again.");
        }
    }
}
// Enter your guess (1-100): 50
// Too high! Try again.
// Enter your guess (1-100): 25
// Too low! Try again.
// Enter your guess (1-100): 38
// Too low! Try again.
// Enter your guess (1-100): 44
// Too low! Try again.
// Enter your guess (1-100): 47
// Too high! Try again.
// Enter your guess (1-100): 45
// Congratulations! You guessed the number.

R5. 이중 반목문을 사용한 구구단 출력

// 가로 구구단
Console.WriteLine("가로 구구단");
for (int i = 2; i <= 9; i++)
{
    for (int j = 1; j <= 9; j++)
    {
        Console.Write(i + " x " + j + " = " + i * j + '\t');
    }
    Console.WriteLine();
}
// 세로 구구단
Console.WriteLine("세로 구구단");
for (int i = 1; i <= 9; i++)
{
    for (int j = 2; j <= 9; j++)
    {
        Console.Write(j + " x " + i + " = " + i * j + '\t');
    }
    Console.WriteLine();
}
// 가로 구구단
// 2 x 1 = 2       2 x 2 = 4       2 x 3 = 6       2 x 4 = 8       2 x 5 = 10      2 x 6 = 12      2 x 7 = 14      2 x 8 = 16      2 x 9 = 18
// 3 x 1 = 3       3 x 2 = 6       3 x 3 = 9       3 x 4 = 12      3 x 5 = 15      3 x 6 = 18      3 x 7 = 21      3 x 8 = 24      3 x 9 = 27
// 4 x 1 = 4       4 x 2 = 8       4 x 3 = 12      4 x 4 = 16      4 x 5 = 20      4 x 6 = 24      4 x 7 = 28      4 x 8 = 32      4 x 9 = 36
// 5 x 1 = 5       5 x 2 = 10      5 x 3 = 15      5 x 4 = 20      5 x 5 = 25      5 x 6 = 30      5 x 7 = 35      5 x 8 = 40      5 x 9 = 45
// 6 x 1 = 6       6 x 2 = 12      6 x 3 = 18      6 x 4 = 24      6 x 5 = 30      6 x 6 = 36      6 x 7 = 42      6 x 8 = 48      6 x 9 = 54
// 7 x 1 = 7       7 x 2 = 14      7 x 3 = 21      7 x 4 = 28      7 x 5 = 35      7 x 6 = 42      7 x 7 = 49      7 x 8 = 56      7 x 9 = 63
// 8 x 1 = 8       8 x 2 = 16      8 x 3 = 24      8 x 4 = 32      8 x 5 = 40      8 x 6 = 48      8 x 7 = 56      8 x 8 = 64      8 x 9 = 72
// 9 x 1 = 9       9 x 2 = 18      9 x 3 = 27      9 x 4 = 36      9 x 5 = 45      9 x 6 = 54      9 x 7 = 63      9 x 8 = 72      9 x 9 = 81
// 세로 구구단
// 2 x 1 = 2       3 x 1 = 3       4 x 1 = 4       5 x 1 = 5       6 x 1 = 6       7 x 1 = 7       8 x 1 = 8       9 x 1 = 9
// 2 x 2 = 4       3 x 2 = 6       4 x 2 = 8       5 x 2 = 10      6 x 2 = 12      7 x 2 = 14      8 x 2 = 16      9 x 2 = 18
// 2 x 3 = 6       3 x 3 = 9       4 x 3 = 12      5 x 3 = 15      6 x 3 = 18      7 x 3 = 21      8 x 3 = 24      9 x 3 = 27
// 2 x 4 = 8       3 x 4 = 12      4 x 4 = 16      5 x 4 = 20      6 x 4 = 24      7 x 4 = 28      8 x 4 = 32      9 x 4 = 36
// 2 x 5 = 10      3 x 5 = 15      4 x 5 = 20      5 x 5 = 25      6 x 5 = 30      7 x 5 = 35      8 x 5 = 40      9 x 5 = 45
// 2 x 6 = 12      3 x 6 = 18      4 x 6 = 24      5 x 6 = 30      6 x 6 = 36      7 x 6 = 42      8 x 6 = 48      9 x 6 = 54
// 2 x 7 = 14      3 x 7 = 21      4 x 7 = 28      5 x 7 = 35      6 x 7 = 42      7 x 7 = 49      8 x 7 = 56      9 x 7 = 63
// 2 x 8 = 16      3 x 8 = 24      4 x 8 = 32      5 x 8 = 40      6 x 8 = 48      7 x 8 = 56      8 x 8 = 64      9 x 8 = 72
// 2 x 9 = 18      3 x 9 = 27      4 x 9 = 36      5 x 9 = 45      6 x 9 = 54      7 x 9 = 63      8 x 9 = 72      9 x 9 = 81

R6. 배열 요소의 최대값과 최소

Random rand = new Random();
int len = rand.Next(3, 11); // 길이도 랜덤
int[] a = new int[len];
for (int i = 0; i < len; i++)
{
    a[i] = rand.Next(-100, 100);
}
int max = -101; // 최대는 최소값부터
int min = 101; // 최소는 최대값부터
for (int i = 0; i < len; i++)
{
    max = Math.Max(max, a[i]);
    min = Math.Min(min, a[i]);
}
Console.Write("Array: ");
for (int i = 0; i < len; i++)
{
    Console.Write(a[i] + " ");
}
Console.WriteLine();
Console.WriteLine("Max: " + max + ", Min: " + min);
// 출력 예시:
// Array: 53 - 24 - 14 - 58 62 - 58 23
// Max: 62, Min: -58

R7. 행맨 게임

string secretWord = "hangman";
char[] guessWord = { '_', '_', '_', '_', '_', '_', '_' }; // 초기 배열
int attempts = 6;
bool wordGuessed = false; // 모두 맞췄는가
while (!wordGuessed && attempts > 0)
{
    Console.WriteLine("맞춘 문자: " + new string(guessWord));
    Console.Write("알파벳을 입력해주세요. (남은 횟수: " + attempts + ") -> ");
    string s_in = Console.ReadLine();
    char ans;
    if (char.TryParse(s_in, out ans) && ((ans >= 'a' && ans <= 'z') || (ans >= 'A' && ans <= 'Z'))) // 입력이 알파벳인 경우
    {
        if (secretWord.Contains(ans)) // 입력된 알파벳이 정답 문자열에 포함된 경우
        {
            int tmpIndex = secretWord.IndexOf(ans);
            while (tmpIndex != -1) // 문자열 끝까지 체크하여, ans해당 하는 알파벳 찾기 
            {
                if (guessWord[tmpIndex] == ans) // 이미 찾은 위치의 알파벳이라면
                {
                    tmpIndex = secretWord.IndexOf(ans, tmpIndex + 1); // 다음 인덱스의 알파벳 체크
                }
                else // 중복으로 찾은 알파벳이 아니라면
                {
                    guessWord[tmpIndex] = ans;
                    Console.WriteLine("맞췄습니다!");
                    string s_ret = new string(guessWord); // 맞춘 char배열을 string으로 변경하기
                    if (s_ret == secretWord)// 변경한 문자열이 정답 문자열이라면
                    {
                        wordGuessed = true; // 모두 맞춤 true;
                    }
                    break; // 중복안된 문자를 찾았다면 브레이크
                }
            }
            if (tmpIndex == -1) // 모든 문자 체크했는데, 중복된 알파벳인 경우
            {
                Console.WriteLine("중복된 알파벳입니다! 다시 입력해주세요.");
            }
        }
        else // 입력된 알파벳이 정답 문자열에 포함 안될 경우 기회 - 1
        {
            attempts--;
            Console.WriteLine("틀렸습니다!");
        }
    }
    else // 알파벳이 아니면 다시 입력
    {
        Console.WriteLine("다시 입력해주세요.");
    }
}
if (wordGuessed) // 모두 맞춘경우
{
    Console.WriteLine("모두 맞췄습니다!");
}
else // 횟수를 다 소모한 경우
{
    Console.WriteLine("맞추기 실패!");
}
// 예시:
// 알파벳을 입력해주세요. (남은 횟수: 6) -> 123
// 다시 입력해주세요.
// 알파벳을 입력해주세요. (남은 횟수: 6) -> q
// 틀렸습니다!
// 알파벳을 입력해주세요. (남은 횟수: 5) -> w
// 틀렸습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> h
// 맞췄습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> a
// 맞췄습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> a
// 맞췄습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> a
// 중복된 알파벳입니다! 다시 입력해주세요.
// 알파벳을 입력해주세요. (남은 횟수: 4) -> n
// 맞췄습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> n
// 맞췄습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> n
// 중복된 알파벳입니다! 다시 입력해주세요.
// 알파벳을 입력해주세요. (남은 횟수: 4) -> g
// 맞췄습니다!
// 알파벳을 입력해주세요. (남은 횟수: 4) -> m
// 맞췄습니다!
// 모두 맞췄습니다!

R8. 숫자 야구 게임

 - 해당 문제는 예와 힌트가 다 뒤죽박죽이다.
 - 우선 문제 설명의 예에서 컴퓨터가 427일 선택하고 사용자가 123을 입력했을 때, 2는 자리수(십의 자리)도 맞고 숫자도 맞으니 1스트라이크 0볼이 맞다.
 - 내가 잘못 이해했나 체크해봤지만 예상 출력을 확인하고 예가 틀렸다 확신했다.

 - 예상 출력 중 789를 입력했을 때를 보면 십의 자리(8)은 스트라이크고 나머지 두 숫자는 컴퓨터 입력과 숫자는 맞지만 자리수가 다른 경우라, 1스트라이크 2볼이다.
 - 힌트도 잘못됐다. 분명 문제에서 "컴퓨터가 고른 3자리 숫자는 모두 다른 숫자로 이루어져 있습니다."라고 나와있다. random으로 받은 숫자가 중복이 안되도록 구현을 따로 해야 한다.

 - 코드:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Metrics;

int[] targetNumber = new int[3]; // 컴퓨터가 선택한 숫자
int[] userGuess = new int[3]; // 유저가 추측한 숫자
int strikes = 0; // 자릿수와 숫자가 동일한 경우의 개수
int balls = 0; // 자릿수는 맞지 않지만 숫자가 포함된 경우의 개수
bool guessedCorrectly = false; // 사용자가 숫자를 정확히 맞췄는지를 나타내는 불리언 변수
int cnt = 0; // 내가 시도한 횟수
Random rand = new Random(); // 난수 생성용
Dictionary<int, bool> comCheck = new Dictionary<int, bool>(); // 컴퓨터는 중복된 숫자 선택 불가,
                                                              // 배열도 가능, 범위가 0 ~ 9이니까
//HashSet<int> comCheck2 = new HashSet<int>(); // C++의 set도 가능
//comCheck2.Add(1); // 반환값이 bool이라 추가한 숫자 중복이면 false, 아니라면 true;

int idx = 0; // 컴퓨터가 선택한 숫자의 자리

// 컴퓨터는 012 같은 경우도 선택가능하게 하기
while (idx != 3) // 인덱스가 3이면 종료, 크기가 3이니까
{
    int num = rand.Next(0, 10);
    if (!comCheck.ContainsKey(num)) // 중복된 숫자가 아니라면
    {
        targetNumber[idx] = num;
        comCheck[num] = true; // 숫자 중복 체크
        idx++;
    }
}
// 컴퓨터가 선택한 숫자, 디버깅 용도
Console.Write("Computer-generated number: ");
for (int i = 0; i < 3; i++)
{
    Console.Write(targetNumber[i]);
}
Console.WriteLine();

while (!guessedCorrectly) // 맞출때까지
{
    // 스트라이크, 볼 초기화
    strikes = 0;
    balls = 0;
    Dictionary<int, bool> userCheck = new Dictionary<int, bool>(); // 유저 중복숫자 체크용, 계속 초기화해야 함
    Console.Write("Enter your guess (3 digits): ");
    string s_in = Console.ReadLine();

    //int tmpNum; // 문자열 -> 숫자 변환 체크용
    //if (s_in.Length == 3 && int.TryParse(s_in, out tmpNum)) // 길이가 3이고, 모두 숫자일 경우(027은 27에 해당하므로 가능)
    if (s_in.Length == 3 && int.TryParse(s_in, out _)) // "_" -> 반환값 필요 없을때 사용,
    {
        char[] tmpArray = s_in.ToCharArray(); // 문자열을 char형 배열로 변환(s_in[1] 안됨)
        for (int i = 0; i < 3; i++)
        {
            userGuess[i] = tmpArray[i] - '0'; // 유저가 추측한 숫자 배열에 입력한 숫자 담기
        }
        bool isDuplicate = false; // 사용자 입력 숫자 중복체크용
        for (int i = 0; i < 3; i++)
        {
            if (!userCheck.ContainsKey(userGuess[i])) // 사용자가 입력한 숫자가 중복인지 체크
            {
                userCheck[userGuess[i]] = true;
            }
            else
            {
                isDuplicate = true; // 중복되었다면 중복 체크하기
                break; // 더 체크할 필요 없이 종료
            }
        }
        if (isDuplicate) // 유저가 중복된 숫자를 입력했다면
        {
            Console.WriteLine("서로 다른 숫자를 입력해주세요.");
            continue; // 다시 처음으로
        }

        // 여기까지 왔으면 길이가 3개인 서로 다른 숫자를 입력받았다는 뜻
        cnt++; // 시도 횟수 증가
        // 스트라이크, 볼 체크하기
        for (int i = 0; i < 3; i++)
        {
            if (userGuess[i] == targetNumber[i]) // 자릿수와 숫자가 동일한 경우
            {
                // 스트라이크 증가시키고 다음 자릿수로
                strikes++;
                continue;
            }
            for (int j = 0; j < 3; j++) // 유저 i번째 숫자와 컴퓨터 j번째 숫자 체크하여 ball체크
            {
                // 자리수는 다르지만 같은 숫자일 경우
                // if(i == j) continue; 를 해야하지만, 정답에 지장이 없고, 인덱스가 작아서 체크하는 게 더 느릴거라 판단
                if (userGuess[i] == targetNumber[j]) balls++;
            }
        }
        Console.WriteLine(strikes + " Strike(s), " + balls + " Ball(s)");
        if (strikes == 3) guessedCorrectly = true; // 다 맞췄다면 종료
    }
    else // 길이가 3이 아니거나, 모두 숫자가 아니라면 다시 입력, 횟수 증가 안하기
    {
        Console.WriteLine("다시 입력해주세요.");
    }
}
Console.WriteLine("Congratulations! You've guessed the number in " + cnt + " attempts.");
// 출력 예시:
// Computer - generated number: 012
// Enter your guess (3 digits): 123
// 0 Strike(s), 2 Ball(s)
// Enter your guess (3 digits): 013
// 2 Strike(s), 0 Ball(s)
// Enter your guess (3 digits): 213
// 1 Strike(s), 1 Ball(s)
// Enter your guess (3 digits): 000
// 서로 다른 숫자를 입력해주세요.
// Enter your guess (3 digits): 123123
// 다시 입력해주세요.
// Enter your guess (3 digits): asdgadsg
// 다시 입력해주세요.
// Enter your guess (3 digits): 012
// 3 Strike(s), 0 Ball(s)
// Congratulations! You've guessed the number in 4 attempts.

 

 

목차