C# 연습문제 : 코드의 흐름 제어 (뇌를 자극하는 C# 5.0)

2022. 9. 13. 23:54문제/C# 연습문제

1.다음과 같은 결과를 출력하는 프로그램을 for문을 이용하여 작성하세요. 규칙은 첫 번째 줄에 별 하나, 두 번째 줄에 별 둘, 세번째 줄에 별 셋 이런 식으로 5개의 별이 찍힐 때까지 반복합니다. (다중 for문을 이용해서 만드시오)

 

  public class Program
    {
        private static void Main(string[] args)
        {
            for (int i = 1; i < 6; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }
        }
    }

 

2.  반대로 별이 5개부터 시작해서 1개로 줄어드는 프로그램을 for문을 이용하여 작성하세요.

        private static void Main(string[] args)
        {
            for (int i = 5; i > 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    Console.Write("*");
                }

                Console.WriteLine();
            }
        }

 

 

3. 1번과 2번을 for문 대신 while 문으로 바꿔서 작성하세요.

 public class Program
    {
        private static void Main(string[] args)
        {
            int count = 1;
            int lenth = 0;

            while (count <= 5)
            {
                if (lenth < count)
                {
                    Console.Write("*");
                    lenth++;
                }
                else if (lenth == count)
                {
                    Console.WriteLine();
                    count++;
                    lenth = 0;
                }
            }
        }
    }

n번째 줄의 갯수를 나타태는 count 변수와, 별의 갯수를 나타내는 lenth 변수를 이용해 줄마다 한개씩 늘도록 구현하였습니다.

 

 

4. 다음과 같이 사용자로부터 입력받은 횟수만큼 별을 반복 출력하는 프로그램을 작성하세요. 단, 입력받은 수가 0보다 작거나 같을 경우 "0보다 같거나 작은 숫자는 사용할 수 없습니다."라는 메세지를 띄우고 프로그램을 종료합니다.

public class Program
    {
        private static void Main(string[] args)
        {
            Console.Write("반복 횟수를 입력하세요 : ");

            string countText = Console.ReadLine();

            int count = int.Parse(countText);

            if (count <= 0)
            {
                Console.WriteLine("0보다 같거나 작은 숫자는 사용할 수 없습니다.");
            }
            else
            {
                for (int i = 0; i <= count; i++)
                {
                    for (int j = 0; j < i; j++)
                    {
                        Console.Write("*");
                    }

                    Console.WriteLine();
                }
            }
        }
    }