연습문제/C# 연습문제

16. 2차원 배열 출력하기(다차원)

규남 2023. 8. 27. 00:07
반응형

<소스 코드>

namespace Test
{
    internal class Program
    {
        static void Main(string[] args)
        {
            int[,] array = new int[2, 2] { { 1, 2 }, { 3, 4 } };
            int count = 0;

            // 1번 foreach를 이용한 출력
            foreach(int i in array)
            {
                Console.Write(i + " ");
                count++;
                if (count == 2)
                {
                    Console.WriteLine();
                    count = 0;
                }
            }
            
            Console.WriteLine();

            // 2번 for문을 이용한 출력
            for(int i = 0; i < array.GetLength(0); i++)
            {
                for (int j = 0; j < array.GetLength(1); j++)
                    Console.Write(array[i, j] + " ");
                Console.WriteLine();
            }

            Console.WriteLine();

            // 3번 string.Join을 이용한 출력
            Console.WriteLine(string.Join(", ", array.Cast<int>()));
            
        }
    }
}

<결과 확인>

728x90
반응형