24.10.02 Day56

최지원·2024년 10월 2일

함수

using System;

namespace ConsoleApp1 {
    internal class ex08 {
        static void Main() {
            // 함수 안에서 함수를 선언/정의하면 안됨
            myFunc();
            myFunc2(10);
            string result = myFunc3();
            Console.WriteLine(result);

            float dimension = myFunc4(10, 20);
            Console.WriteLine(dimension);
        }
        // 서브 함수(사용자 정의 함수)선언
        // 패턴
        // 반환타입 함수이름(매개변수){
        //      실행문...
        //}
        static void myFunc() {
            Console.WriteLine("myFunc() 호출됨");
        }

        // static : 정적(고정), 코드 호출시에 고정된 주소값을 가지는 것을 의미
        //          안정적인 코드 수행이 가능(시작점, 전역변수, 중요한 변수나 데이터)

        // 함수의 4가지 패턴
        // 매개변수 X 반환값 X
        static void myFunc1() {
            Console.WriteLine("myFunc1() 호출됨");
        }

        // 매개변수 O 반환값 X
        static void myFunc2(int param) {
            Console.WriteLine("myFunc1() 호출됨");
            Console.WriteLine($"매개변수{param}");
        }
        // 매개변수 X 반환값 O
        static string myFunc3() {
            Console.WriteLine("myFunc() 호출됨");
            return "하이~";
        }

        static float myFunc4(int width, int height) {
            return width * height;
        }
    }
}

연습문제

using System;

namespace ConsoleApp1 {
    internal class ex09 {
        static void Main() {
            // 연습문제7
            // 1. 원의 둘레 구하는 함수를 선언하고
            //    매개변수로 반지름을 입력하면 원주율을 반환하여 출력
            //    원의 둘레 공식 : 2 x 반지름 x 3.14
            double result = pie(10);
            Console.WriteLine(result);

            // 2. 정수 3개를 매개변수로 입력받고, 그 중 가장 큰 수를 반환하는 함수 선언
            int a = 10;
            int b = 20;
            int c = 30;

            int maxValue = max_num(a, b, c);
            Console.WriteLine("\n<문제2>");
            Console.WriteLine("가장 큰 숫자 : " + maxValue);

            //3. 문자열 압축 함수
            //주어진 문자열에서 연속된 문자를 압축하는 CompressString(string input) 함수를
            //작성하세요.
            //예를 들어, 입력이 "aaabbcccc"일 경우 "a3b2c4"를 반환하도록 하세요.
            Console.WriteLine("\n<문제3>");
            CompressString("aaabbcccc");
        }
        // 1)
        static double pie(int half) {
            Console.WriteLine("<문제1>");
            return half * 2 * 3.14;
        }

        // 2)
        static int max_num(int a, int b, int c) {
            if (a > b && a > c) {
                return a;
            } else if (b > a && b > c) {
                return b;
            } else {
                return c;
            }
        }

        // 3)
        static void CompressString(string input) {
            int[] alphbet = new int[26];

            char[] cArray = input.ToCharArray();

            for (int i = 0; i < cArray.Length; i++) {
                for(int j = 0; j < alphbet.Length; j++) {
                    if(cArray[i] == 'a' + j) {
                        alphbet[j]++;
                    }
                }
            }
            Console.WriteLine(string.Join(',',alphbet));
            for(int n = 0; n < alphbet.Length; n++) {
                //Console.Write($"{(char)'a'+}")
            }
        }
    }
}

배열, 큐, stack

using System;

namespace ConsoleApp1 {
    internal class ex10 {
        static void Main(string[] args) {
            int[] arrayNum = { 10, 20, 30 };
            int[] arrayNum2 = { 10, 20, 30 };
            int[] arrayNum3 = new int[3];
            arrayNum3[0] = 10;

            int[][] array2DNum = [[10, 20], [30, 40]];
            int[][] array2DNum2 = new int[3][];
            array2DNum2[0] = [10, 20, 30];
            array2DNum2[1] = [40, 50, 60];
            array2DNum2[2] = [70, 80, 90];

            // 고정된 타입
            List<int> list = new List<int>();
            list.Add(10);
            list.Add(20);
            foreach (int n in list) {
                Console.WriteLine(n);
            }
            for (int i = 0; i < list.Count; i++) {
                Console.WriteLine(list.ElementAt(i));
            }

            // 다양한 타입
            ArrayList arrayList = new ArrayList();
            arrayList.Add(10);
            arrayList.Add("20");
            arrayList.Add(3.14f);

            // var : 타입이 고정되지 않은 변수형
            foreach (var item in arrayList) {
                // object 타입으로 arraylist 저장
                if (typeof(int) == item.GetType()) {
                    Console.WriteLine("int타입입니다.");
                    int num = Convert.ToInt32(item);
                    Console.WriteLine(num);
                }
                if (typeof(string) == item.GetType()) {
                    Console.WriteLine("String타입입니다.");
                }
                Console.WriteLine(item);
            }
            // 큐 Queue : FIFO 타입의 데이터 구조
            Queue<int> queue = new Queue<int>();
            queue.Enqueue(10);
            queue.Enqueue(20);
            queue.Enqueue(30);
            while (queue.Count > 0) {
                Console.WriteLine(queue.Dequeue());
            }

            // 스택 : FIFO
            Stack<int> stack = new Stack<int>();
            stack.Push(10);
            stack.Push(20);
            stack.Push(30);
            while (stack.Count > 0) {
                Console.WriteLine(stack.Pop());
            }

            // 예외처리하기
            // 오류 발생시 처리하는 코드 추가
            Console.Write("나눌 숫자를 입력하세요");
            int divider = int.Parse(Console.ReadLine());
            try {
                Console.WriteLine(10 / divider);
            } catch (Exception e) {
                Console.WriteLine("예외 상황 : " + e.Message);
            }
        }
    }
}

클래스

using System;
using System.Collections.Generic;

namespace ConsoleApp1 {
    //클래스 선언
    //객체지향 프로그래밍(OOP, Object Oriented Programming)
    //사물을 클래스로 추상화(코드화)하는 것
    //예) 강아지 : 속성(변수)과 행동(함수)

    //접근제한자 
    //public : 다른 클래스에서 자신의 변수나 함수에 접근하게 열어줌. 공개한다는 의미.
    //private : 기본값(생략시), 자신만 변수나 함수를 사용가능.
    class Dog {
        public string name = "까미";
        public void eat() {
            Console.WriteLine("먹는다");
        }
    }
    //메인 클래스
    internal class ex11 {
        static void Main() {
            //클래스를 메모리에 옮겨놓아야 실행가능하다.
            //객체(인스턴스)를 생성한다. 

            //클래스 변수이름 = new 클래스();
            Dog dog = new Dog();
            //변수(객체)이름 뒤에 점.을 찍으면 변수와 함수에 접근 가능하다.
            Console.WriteLine(dog.name);
            //Console.WriteLine(dog.eat()); //eat의 반환값이 void는 출력할 수 없다.
            dog.eat();

            Student student = new Student();
            student.study();
            Console.WriteLine(student.age);

            Farm farm = new Farm();
            farm.plant(); farm.plant(); farm.plant(); farm.plant(); farm.plant();
            Console.WriteLine(farm.getCarrotCount());

            Calc calc = new Calc();
            calc.sum(10, 20);
            Console.WriteLine(calc.result);
        }
    }

    //연습문제 8
    //1. 학생 Student 클래스를 설계해보자.
    //  학생의 속성은 int age(초기값 20), 학생의 행동은 study() 공부한다.
    // student객체를 생성하고, 속성과 행동을 출력하시오.
    class Student {
        public int age = 20;
        public void study() {
            Console.WriteLine("공부한다.");
        }
    }

    //2. 당근농장 Farm 클래스를 설계해보자.
    //  속성(변수)로 당근의 갯수를 가지고 있다. 초기값 0
    //  행동(함수)로 plant(생산)함수를 호출하면, 자신이 가지고 있는 당근의 갯수를 +1한다.
    // plant함수를 5번 실행한 후에, 당근의 갯수를 출력하시오.
    class Farm() {
        //멤버 변수
        private int carrot = 0;  //외부에 자신의 중요한 값을 감춘다. 캡슐화(은닉)한다.

        //getter함수
        public int getCarrotCount() {
            return carrot;
        }
        //setter함수
        public void setCarrotCount(int carrot) {
            //this : 자신의 클래스를 의미함.
            this.carrot = carrot;
        }

        public void plant() {
            carrot++;
        }
    }
    //3. 계산기 Calc 클래스를 설계해보자.
    // 속성(변수)로 결과값 double타입을 가지고 있고,
    // sum, sub, mul, div (더하기,빼기,곱하기,나누기)를 수행한다.
    // 매개변수는 double형 2개이고, 반환형은 double이다.
    // Calc 클래스 객체를 사용하여, 사칙연산을 수행해 보자.
    class Calc {
        public double result = 0.0;
        public void sum(double x, double y) {
            this.result = x + y;
        }
        public void sub(double x, double y) {
            this.result = x - y;
        }
        public void mul(double x, double y) {
            this.result = x * y;
        }
        public void div(double x, double y) {
            this.result = x / y;
        }
    }
}

클래스 상속

using System;
using System.Collections.Generic;

namespace ConsoleApp1 {
    internal class ex12 {
        static void Main(string[] args) {
            CoffeeRobot cRobot = new CoffeeRobot();
            cRobot.work(); //부모의 자산을 자식이 물려받은 것.
            Console.WriteLine(cRobot.price);

            cRobot.make();
        }
    }
    //클래스의 상속: 부모클래스의 자산(변수,함수)을 자식클래스에게 넘겨줌.
    //공통된 클래스를 이용하여, 코드중복을 줄이거나 체계적인 코드 작성에 용이함.
    class Robot {
        public int price = 1000; //속성
        public void work() { //행동
            Console.WriteLine("일한다");
        }
    }
    //Robot을 상속
    class CoffeeRobot : Robot {
        public string name = "커피로봇";
        public void make() {
            Console.WriteLine("커피를 만든다.");
        }
    }
    class DeliveryRobot : Robot {
        public string name = "배달로봇";
        public void delivery() {
            Console.WriteLine("배달한다.");
        }
    }
}

생성자 함수

using System;

namespace ConsoleApp1 {
    internal class ex13 {
        static void Main() {
            Book book = new Book();
            Console.WriteLine(book.price);
            Book book2 = new Book(2000);
            Console.WriteLine(book2.price);
        }
    }
    //생성자함수 : 클래스객체 생성시 자동으로 호출되는 함수
    // 용도: 값의 초기화
    class Book {
        public int price = 1000;//속성

        //생성자함수는 public이고, 반환형이 없음. 이름은 클래스이름과 동일.
        public Book() {
            Console.WriteLine("생성자함수 호출됨.");
        }
        //메소드 오버로딩: 매개변수의 타입과 갯수를 다르게 함으로
        //              동일한 함수이름을 사용하도록 허락하는 것.
        public Book(int price) {
            this.price = price;
        }
        void read() { //행동
            //읽는다.
        }
    }
}

0개의 댓글