정신과 시간의 방
카테고리
작성일
2022. 7. 18. 23:58
작성자
risehyun

C#과 유니티로 만드는 MMORPG 게임 개발 시리즈를 수강하며 연습문제를 풀어보았다.

 


    class Program
    {
        // <연습 문제 : 구구단>
        static void Main(string[] args)
        {
            for (int i = 2; i <= 9; i++)
            {
                for (int j = 1; j <= 9; j++)
                {
                    Console.WriteLine($"{i} * {j} = {i*j}");
                }
            }
        }
    }
        // <연습 문제 : 간단한 별 피라미드>
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
        }
    class Program
    {
        static int Factorial(int n)
        {
            int ret = 1;
            for (int num = 1; num <= n; num++)
            {
                ret *= num;
            }
            return ret;
        }

        // <연습 문제 : 팩토리얼>
        static void Main(string[] args)
        {
                // 5! = 5 * 4 * 3 * 2 * 1
                // n! = n * (n-1) ... * 1 (n >= 1)
                int ret = Factorial(5);
                Console.WriteLine(ret);
        }
    }
        // <연습 문제 : 재귀함수로 팩토리얼 구현 - 오류>
        // 재귀 함수 : 함수 안에서 다시 자신을 호출하는 것
class Program
    {
        static int Factorial(int n)
        {
            return n * Factorial(n - 1);
        }


        static void Main(string[] args)
        {
                // 5! = 5 * (4!)
                // 5! = 5 * 4 * 3 * 2 * 1
                // n! = n * (n-1) ... * 1 (n >= 1)
                int ret = Factorial(5);
                Console.WriteLine(ret); // 종료 조건을 지정하지 않았기 때문에 스택 오버플로우가 발생함
        }
    }
    
            // <연습 문제 : 재귀함수로 팩토리얼 구현 - 정상작동>
        class Program
    {
        static int Factorial(int n)
        {
            if (n <= 1) // 종료 조건 추가
                return 1;
            return n * Factorial(n - 1);
        }


        static void Main(string[] args)
        {
                // 5! = 5 * (4!)
                // 5! = 5 * 4 * 3 * 2 * 1
                // n! = n * (n-1) ... * 1 (n >= 1)
                int ret = Factorial(5);
                Console.WriteLine(ret); // 종료 조건을 지정했기 때문에 정상 실행됨
        }
    }

 

'C#' 카테고리의 다른 글

220817 Interface (인터페이스)  (0) 2022.08.17
[C#] 일반화(Generic)  (0) 2022.08.16
220816 배열과 컬렉션  (0) 2022.08.16
[C#] 문법 정리  (0) 2022.07.17
220716 C# 람다식  (0) 2022.07.16