C# 연습문제 : 배열,컬렉션 (뇌를 자극하는 C# 5.0)

2022. 9. 18. 22:03문제/C# 연습문제

1. 두 행렬 A와 B의 곱을 2차원 배열을 이용하여 계산하는 프로그램을 작성하세요.

using System;

namespace BookTestC
{
    public class Program
    {
        private static void Main(string[] args)
        {
            int[,] a = new int[2, 2] { { 3, 2 }, { 1, 4 } };
            int[,] b = new int[2, 2] { { 9, 2 }, { 1, 7 } };

            int[,] result = new int[2, 2];

            result = Multiplication(a, b);

            Console.WriteLine("Result = [{0} , {1}]", result[0, 0], result[1, 0]);
            Console.WriteLine("         [{0} , {1}]", result[1, 0], result[1, 1]);
        }

        public static int[,] Multiplication(int[,] a, int[,] b)
        {
            int[,] result = new int[2, 2]
            {
                { a[0,0] * b[0,0], a[0,1] * b[0,1] },
                { a[1,0] * b[1,0], a[1,1] * b[1,1] }
            };

            return result;
        }
    }
}

 

 

 

3. 다음 코드의 출력 결과는 무엇일까요?

using System;
using System.Collections;

namespace BookTestC
{
    public class Program
    {
        private static void Main(string[] args)
        {
            Stack stack = new Stack();
            stack.Push(1);
            stack.Push(2);
            stack.Push(3);
            stack.Push(4);
            stack.Push(5);

            while (stack.Count > 0)
            {
                Console.WriteLine(stack.Pop());
            }
        }
    }
}

stack은 나중에 들어온 데이터가 먼저나가는 구조이기 때문에 5,4,3,2,1 순으로 출력이된다.

 

4.다음 코드의 출력 결과는 무엇일까요?

using System;
using System.Collections;

namespace BookTestC
{
    public class Program
    {
        private static void Main(string[] args)
        {
            Queue que = new Queue();

            que.Enqueue(1);
            que.Enqueue(2);
            que.Enqueue(3);
            que.Enqueue(4);
            que.Enqueue(5);

            while (que.Count > 0)
            {
                Console.WriteLine(que.Dequeue());
            }
        }
    }
}

queue는 나중에 들어온 데이터 순으로 나가기 때문에 1,2,3,4,5순으로 출력된다.

 

 

4. 해시테이블을 이용해 회사와 URL을 출력하는 프로그램을 작성하세요.

using System;
using System.Collections;

namespace BookTestC
{
    public class Program
    {
        private static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();

            ht["회사"] = "Microsoft";
            ht["URL"] = "www.Microsoft.com";

            Console.WriteLine("회사 :  {0}", ht["회사"]);
            Console.WriteLine("URL :  {0}", ht["URL"]);
        }
    }
}