[C#] 코드와 흐름 제어

vector·2025년 8월 29일

C# 공부

목록 보기
2/2

1. if와 else

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        static void Main(string[] args)
        {
            int hp = 10;
            bool isDead = (hp <= 0);

            if (isDead)
            {
                Console.WriteLine("You are dead!");
            }
            else
            {
                Console.WriteLine("You are alive!");
            }



            int choice = 0; // 0: 가위 1: 바위 2: 보

            if (choice == 0)
            {
                Console.WriteLine("가위 입니다.");
            }
            else if (choice == 1)
            {
                Console.WriteLine("바위 입니다.");
            }
            else
            {
                Console.WriteLine("보 입니다.");
            }
        }
    }
}

2. switch

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        static void Main(string[] args)
        {
            int choice = 0; // 0: 가위 1: 바위 2: 보

            switch(choice)
            {
                case 0:
                    Console.WriteLine("가위 입니다");
                    break;
                case 1:
                    Console.WriteLine("바위 입니다");
                    break;
                case 2:
                    Console.WriteLine("보 입니다");
                    break;

            }



            // 삼항 연산자

            int number = 25;
            bool isPair = ((number % 2) == 0 ? true : false); // 조건 ? 참 : 거짓
        }
    }
}

3. 가위바위보 게임

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             1. 랜덤으로 가위바위보 중에 하나를 정하는 것
             2. 사용자의 입력을 받아 가위바위보 값을 지정
             3. 승 무 패 중 하나를 출력

             0: 가위 1: 바위 2: 보
             */
            // 1. 랜덤하게 하나의 숫자 선택
            Random rand = new Random();
            int aiChoice = rand.Next(0, 3); // 0 ~ 2 사이의 랜덤 값

            // 2. 사용자의 입력값 받기
            int choice = Convert.ToInt32(Console.ReadLine()); // 사용자의 입력값을 받아 int값으로 변환

            switch (choice)
            {
                case 0:
                    Console.WriteLine("당신의 선택은 가위입니다.");
                    break;
                case 1:
                    Console.WriteLine("당신의 선택은 바위입니다.");
                    break;
                case 2:
                    Console.WriteLine("당신의 선택은 보입니다.");
                    break;
            }

            switch (aiChoice)
            {
                case 0:
                    Console.WriteLine("컴퓨터의 선택은 가위입니다.");
                    break;
                case 1:
                    Console.WriteLine("컴퓨터의 선택은 바위입니다.");
                    break;
                case 2:
                    Console.WriteLine("컴퓨터의 선택은 보입니다.");
                    break;
            }

            // 3. 승리 무승부 패배

            if (choice == aiChoice)
            {
                Console.WriteLine("무승부 입니다.");
            }
            else if ((choice == 1 && aiChoice == 2) || 
                     (choice == 2 && aiChoice == 0) || 
                     (choice == 0 && aiChoice == 1))
            {
                Console.WriteLine("졌습니다.");
            }
            else
            {
                Console.WriteLine("이겼습니다.");
            }

        }
    }
}

4. 상수와 열거형

상수

// 상수를 사용

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
             1. 랜덤으로 가위바위보 중에 하나를 정하는 것
             2. 사용자의 입력을 받아 가위바위보 값을 지정
             3. 승 무 패 중 하나를 출력

             0: 가위 1: 바위 2: 보
             */
            const int ROCK = 1;
            const int PAPER = 2;
            const int SCISSORS = 0;

            // 1. 랜덤하게 하나의 숫자 선택
            Random rand = new Random();
            int aiChoice = rand.Next(0, 3); // 0 ~ 2 사이의 랜덤 값

            // 2. 사용자의 입력값 받기
            int choice = Convert.ToInt32(Console.ReadLine()); // 사용자의 입력값을 받아 int값으로 변환

            switch (choice)
            {
                case SCISSORS:
                    Console.WriteLine("당신의 선택은 가위입니다.");
                    break;
                case ROCK:
                    Console.WriteLine("당신의 선택은 바위입니다.");
                    break;
                case PAPER:
                    Console.WriteLine("당신의 선택은 보입니다.");
                    break;
            }

            switch (aiChoice)
            {
                case SCISSORS:
                    Console.WriteLine("컴퓨터의 선택은 가위입니다.");
                    break;
                case ROCK:
                    Console.WriteLine("컴퓨터의 선택은 바위입니다.");
                    break;
                case PAPER:
                    Console.WriteLine("컴퓨터의 선택은 보입니다.");
                    break;
            }

            // 3. 승리 무승부 패배

            if (choice == aiChoice)
            {
                Console.WriteLine("무승부 입니다.");
            }
            else if ((choice == ROCK && aiChoice == PAPER) || 
                     (choice == PAPER && aiChoice == SCISSORS) || 
                     (choice == SCISSORS && aiChoice == ROCK))
            {
                Console.WriteLine("졌습니다.");
            }
            else
            {
                Console.WriteLine("이겼습니다.");
            }

        }
    }
}

열거형

// 열거형

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        enum Choice
        {
            Rock = 1,
            Paper = 2,
            Siccors = 0
        }

        static void Main(string[] args)
        {
            /*
             1. 랜덤으로 가위바위보 중에 하나를 정하는 것
             2. 사용자의 입력을 받아 가위바위보 값을 지정
             3. 승 무 패 중 하나를 출력

             0: 가위 1: 바위 2: 보
             */

            // 1. 랜덤하게 하나의 숫자 선택
            Random rand = new Random();
            int aiChoice = rand.Next(0, 3); // 0 ~ 2 사이의 랜덤 값

            // 2. 사용자의 입력값 받기
            int choice = Convert.ToInt32(Console.ReadLine()); // 사용자의 입력값을 받아 int값으로 변환

            switch (choice)
            {
                case (int)Choice.Siccors:
                    Console.WriteLine("당신의 선택은 가위입니다.");
                    break;
                case (int)Choice.Rock:
                    Console.WriteLine("당신의 선택은 바위입니다.");
                    break;
                case (int)Choice.Paper:
                    Console.WriteLine("당신의 선택은 보입니다.");
                    break;
            }

            switch (aiChoice)
            {
                case (int)Choice.Siccors:
                    Console.WriteLine("컴퓨터의 선택은 가위입니다.");
                    break;
                case (int)Choice.Rock:
                    Console.WriteLine("컴퓨터의 선택은 바위입니다.");
                    break;
                case (int)Choice.Paper:
                    Console.WriteLine("컴퓨터의 선택은 보입니다.");
                    break;
            }

            // 3. 승리 무승부 패배

            if (choice == aiChoice)
            {
                Console.WriteLine("무승부 입니다.");
            }
            else if ((choice == (int)Choice.Rock && aiChoice == (int)Choice.Paper) || 
                     (choice == (int)Choice.Paper && aiChoice == (int)Choice.Siccors) || 
                     (choice == (int)Choice.Siccors && aiChoice == (int)Choice.Rock))
            {
                Console.WriteLine("졌습니다.");
            }
            else
            {
                Console.WriteLine("이겼습니다.");
            }

        }
    }
}

5. while

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {

        static void Main(string[] args)
        {
            // while 반복문
            int count = 5;

            while (count > 0)
            {
                Console.WriteLine("Hello World");

                count--;
            }

            // 무조건 한번은 실행하고 반복
            do
            {
            } while (count > 0);


            // 거울아 거울아
            string answer;
            do 
            {
                Console.WriteLine("xx는 잘생겼나요? (y/n) : ");
                answer = Console.ReadLine();
            } while (answer != "y");

            Console.WriteLine("정답입니다.");
        }
    }
}

6. for

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {

        static void Main(string[] args)
        {
            int count = 0;
            while(count < 5)
            {
                Console.WriteLine("Hello World");
                count++;
            }

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("Hello World");
            }
        }
    }
}

7. break, continue

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = 97; // 1, 97로만 나뉘는 숫자

            bool isPrime = true;

            for (int i = 2; i < num; i++)
            {
                if (num % i == 0)
                {
                    isPrime = false;
                    Console.WriteLine("소수가 아닙니다.");
                    break;
                }
                
            }

            if (isPrime)
            {
                Console.WriteLine("소수입니다.");
            }
            else if (isPrime)
            {
                Console.WriteLine("소수가 아닙니다.");
            }



            /////////////////////////////////////////////////
            for (int i = 0; i <= 100; i++)
            {
                if ((i % 3) != 0)
                    continue;


                Console.WriteLine($"3으로 나뉘는 숫자 발견 : {i}");
            }
        }
    }
}

8. 함수

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        // 메소드 함수
        // 한정자 반환형식 이름 (매개 변수 목록)
        static void HelloWorld()
        {
            Console.WriteLine("Hello World");
        }

        // 덧셈 뺄셈
        static int Add(int a, int b)
        {
            return a + b;
        }

        static void AddOne(ref int number)
        {
            number = number + 1;
        }

        static void AddO(int number)
        {
            number = number + 1;
        }

        static void Main(string[] args)
        {
            HelloWorld();
            
            // 1 + 3 => 4
            Console.WriteLine(Add(1, 3));


            int a = 0;
            Program.AddO(a);
            Console.WriteLine(a); // 출력 0

            Program.AddOne(ref a);
            Console.WriteLine(a); // 출력 1
        }
    }
}

9. ref out

using System.Collections.Specialized;

namespace Cshap
{
    class Program
    {
        static void AddOne(ref int number)
        {
            number = number + 1;
        }

        static int AddO(int number)
        {
            return number + 1;
        }

        static void Swap(ref int a, ref int b)
        {
            int c = a;
            a = b;
            b = c;
        }

        static void Divide (int a, int b, out int result1, out int result2)
        {
            result1 = a / b;
            result2 = a % b;
        }

        static void Main(string[] args)
        {
            //int a = 0;
            //Program.AddOne(ref a);
            //Console.WriteLine(a);
            //
            //a = Program.AddO(a); // 이 방식이 더 좋음
            //Console.WriteLine(a);


            int num1 = 1;
            int num2 = 2;
            Program.Swap(ref num1, ref num2);

            Console.WriteLine(num1);
            Console.WriteLine(num2);


            int num3 = 10;
            int num4 = 3;

            int result1;
            int result2;
            Divide(10, 3, out result1, out result2);

            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }
    }
}

10. 오버로딩

using System.Collections.Specialized;
using System.Runtime.InteropServices;

namespace Cshap
{
    class Program
    {
        // 오버로딩 : 함수 이름의 재사용
        static int Add(int a, int b)
        {
            Console.WriteLine("Add int 2개 호출");
            return a + b;
        }

        static int Add(int a, int b, int c)
        {
            Console.WriteLine("Add int 3개 호출");
            return a + b + c;
        }

        static float Add(float a, float b)
        {
            Console.WriteLine("Add float 호출");
            return a + b;
        }

        static int Add(int a, int b, int c = 0, float d = 1.0f, double e = 3.0)
        {
            Console.WriteLine("Add int 복합 호출");
            return a + b + c;
        }

        static void Main(string[] args)
        {
            int ret = Program.Add(1, 2);
            Console.WriteLine(ret);
            float ret2 = Program.Add(2.1f, 3.4f);
            Console.WriteLine(ret2);

            Program.Add(1, 2, d:2.0f); // 중간에 있는 매개변수에만 값을 전달하는 것이 가능
        }
    }
}

11. 연습 문제

using System.Collections.Specialized;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace Cshap
{
    class Program
    {
        // 팩토리얼
        
        // 기본
        //static int Factorial(int n)
        //{
        //    int num = 1;
        //    for (int i = 1; i <= n; i++)
        //    {
        //        num *= i;
        //    }
        //
        //    return num;
        //}
        
        // 재귀
        static int Factorial(int n)
        {
            if (n <= 1)
            {
                return 1;
            }
            return n * Factorial(n - 1);
        }


        static void Main(string[] args)
        {

            /* 별찍기
            for (int i  = 0; i < 5; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }*/


            int ret = Factorial(5);
            Console.WriteLine(ret);
        }
    }
}
profile
게임 클라이언트 프로그래머 준비중 (공부 및 기록용)

0개의 댓글