Lv2.기초 문법 3~6번 문제 (내일배움캠프)

이찬민·2025년 6월 12일
0

3. 팩토리얼 계산

코드

        public static void Main(string[] args)
        {
            Console.WriteLine("Enter a non-negative integer:");
            int number = int.Parse(Console.ReadLine());
            Console.WriteLine($"Factorial of {number} is {Factorial(number)}");
        }

        public static int Factorial(int n)
        {
            if (n < 0)
            {
                throw new ArgumentException("n must be non-negative");
            }

            int result = 1;

            for (int i = 2; i <= n; i++)
            {
                result *= i;
            }

            return result;
        }

출력

해설

Factorial 함수는 int값을 인자로 받음
만약 n이 0보다 작다면 예외를 출력해주고 프로그램을 종료함
이후 for문에 진입을 한 뒤 팩토리얼을 계산 해 준다.

재귀 함수 사용시

        public static int Factorial(int n)
        {
            if (n < 0)
            {
                throw new ArgumentException("n must be non-negative");
            }

            if (n == 0 || n == 1)
            {
                return 1;
            }

            return n * Factorial(n - 1);
        }

for문 대신에 0과 1을 예외처리 해주는 것으로 재귀함수의 형태로 만들 수도 있다.

4. 숫자 맞추기 게임

코드

        public static void PlayGame()
        {
            Random random = new Random();
            int answer = random.Next(1, 101); // 1~100 사이의 랜덤 숫자
            int guess = 0;
            int attempts = 0;

            while (true)
            {
                Console.Write("Enter your guess (1-100):");
                string input = Console.ReadLine();
                if (!int.TryParse(input, out guess))
                {
                    Console.WriteLine("유효한 정수를 입력하세요.");
                    continue;
                }

                attempts++;

                if (guess < answer)
                {
                    Console.WriteLine("Too low! Try again");
                }
                else if (guess > answer)
                {
                    Console.WriteLine("Too high! Try again.");
                }
                else
                {
                    Console.WriteLine($"Congratulations! You guessed the number. Try Count : {attempts}");
                    break;
                }
            }
        }

출력

해설

Random 클래스를 사용하여 1부터 100까지의 숫자에서 값을 하나 구함
이후 맞출때까지 While문을 반복해 줌
이후 유저에게 입력값을 ReadLine으로 받아주고 TryParse기능을 사용해서 예외또한 처리를 해줌

그리고 시도횟수를 추가를 하여 유저로하여금 몇번만에 맞추었는지를 알게 해주는 기능도 넣어줌

만약 추리한 답이 정답보다 낮다면 Too low를 출력, 높다면 Too high를 출력
맞출 시에는 정답이라는 문구와 함께 시도 횟수를 보여줌
그리고 break문을 사용해 무한루프문을 탈출해줌과 동시에 프로그램을 종료함

5. 이중 반복문을 사용한 구구단

코드

public static void Main(string[] args)
{
    Console.WriteLine("Vertical Times Table:");
    PrintVerticalTimesTable();
    Console.WriteLine("\nHorizontal Times Table:");
    PrintHorizontalTimesTable();
}

public static void PrintVerticalTimesTable()
{
    for (int i = 1; i <= 9; i++)
    {
        for (int dan = 2; dan <= 9; dan++)
        {
            Console.Write($"{dan} x {i} = {dan * i}\t");
        }
        Console.WriteLine(); // 각 단 사이에 빈 줄 추가
    }
}

public static void PrintHorizontalTimesTable()
{
    for (int dan = 2; dan <= 9; dan++)
    {
        for (int i = 1; i <= 9; i++)
        {
            Console.Write($"{dan} x {i} = {dan * i}\t");
        }
        Console.WriteLine(); // 각 단 사이에 빈 줄 추가
    }
}

출력

해설

구구단을 세로로 출력하는 부분은 반대로 얘기하면 한번의 연산마다 단수는 증가시키고 곱하는 숫자는 그대로 하면 된다는 것이기에
2중 반복문에서 단수를 안에 배치를 하게되면 되고

가로로 출력하는 부분에서는 반대로 한 줄에 한 단이 나온다는 뜻이기에
단수를 바깥에 배치를 하게 되면 가로와 세로의 구구단배치가 나오게 된다.

설명하기가 어렵다

6. 배열의 최대값 최소값

코드

        public static void Main(string[] args)
        {
            int[] numbers = { 10, 20, 30, 40, 50};
            FindMaxMin(numbers, out int max, out int min);
            Console.WriteLine($"최대값: {max}, 최소값: {min}");
        }

        public static void FindMaxMin(int[] arr, out int max, out int min)
        {
            if (arr == null || arr.Length == 0)
            {
                throw new ArgumentException("배열이 비어 있습니다.");
            }

            max = arr[0];
            min = arr[0];

            for (int i = 1; i < arr.Length; i++)
            {
                if (arr[i] > max)
                {
                    max = arr[i];
                }
                if (arr[i] < min)
                {
                    min = arr[i];
                }
            }
        }

출력

해설

FindMaxMin이라는 함수는 int 배열을 받고 max와 min을 반환하기위해서 out 키워드를 사용 해 준다.
만약 배열이 null이거나 비어있다면 예외처리를 해준다.

이후 min과 max를 배열의 0번 인덱스값으로 초기화 해 준 다음 순회를 하여서 비교를 시작하고 함수를 끝내게 된다.

함수가 끝난 후 Main문에서는 max와 min을 파라미터로 받아서 콘솔로 출력을 해주면 된다.

profile
게임 개발자

0개의 댓글