본문 바로가기

문과 코린이의, [C#] 기록/C# 활용

[문과 코린이의 IT 기록장] C# 활용 - IF문 실습 , 반복문 실습

반응형

[문과 코린이의 IT 기록장] C# 활용 - IF문 실습 , 반복문 실습

[문과 코린이의 IT 기록장] C# 활용 - IF문 실습 , 반복문 실습

 


1. IF문 실습 1 

1. 숫자를 하나 받아들인다. (범위 : 0 - 100)

2. 숫자가 90 이상이면, 다음과 같이 출력한다.
 a. "우수"
 b. "수고하셨습니다."

3. 숫자가 90 미만이면, 다음과 같이 출력한다.

 a. "보통"
 b. "좀 더 노력하세요."

 

1) if1 프로젝트 [ 콘솔 앱 (.NET Framework) ]

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if1
{
    class Program
    {
        static void Main(string[] args)
        {
            iftestMgr obj = new iftestMgr();
            obj.Run();
        }
    }
}

[ ifsetMgr.cs ]

using myLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if1
{
    class iftestMgr
    {
        // 0. 여기부터 프로그램 시작
        public void Run()
        {
            PrintResult(MyUtil.GetDigit());
        }



        // 3. print
        private void PrintResult(int digit)
        {
            if (digit == -1 || digit > 100 || digit < 0)
            {
                Console.WriteLine("잘못된 값을 입력하셨습니다.");
                return; // 이후의 내용들 실행 X.
            }
            else if (digit > 90 && digit <= 100)
            {
                Console.WriteLine("우수");
                Console.WriteLine("수고하셨습니다.");
            }
            else
            {
                Console.WriteLine("보통");
                Console.WriteLine("좀 더 노력하세요.");
            }
        }
    }
}

 

[ 참조 추가 방법 ]

if1 프로젝트에서, MyLibray 프로젝트의 클래스를 참조해 활용하는 방법

ex. using System; 등으로 가져다 쓸 수 있도록 하는 것

 

a. 해당 프로젝트 - [참조] 마우스 우클릭 - [참조 추가] 클릭

b. 참조할 프로젝트 체크 - 확인

c. 결과

MyLibrary 참조 추가된 결과

d. 활용

 


2) if2 프로젝트 [ 콘솔 앱 (.NET Framework) ]

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if2
{
    class Program
    {
        static void Main(string[] args)
        {
            iftestMgr2 obj = new iftestMgr2();
            obj.Run();
        }
    }
}

[ iftestMgr2.cs ]

using myLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if2
{
    class iftestMgr2
    {
        public void Run()
        {
            // MyUtil util = new MyUtil(); 
            PrintResult(MyUtil.GetDigit()); 
            // MyUtil이 static이 되면, 클래스명으로 직접 호출해 줘야 함. new로 인스턴스 생성 불가능.
        }

        // 3. print
        private void PrintResult(int digit)
        {
            if (digit == -1 || digit > 100 || digit < 0)
            {
                Console.WriteLine("잘못된 값을 입력하셨습니다.");
                return; // 이후의 내용들 실행 X.
            }
            else if (digit > 90 && digit <= 100)
            {
                Console.WriteLine("우수");
                Console.WriteLine("수고하셨습니다.");
            }
            else
            {
                Console.WriteLine("보통");
                Console.WriteLine("좀 더 노력하세요.");
            }
        }
    }
}

3) MyLibary 프로젝트 [ 클래스 라이브러리 (.net Framework) ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 클래스 라이브러리 (.net framework)
// 솔루션에서 우클릭 -> 솔루션 빌드를 하면, 이 3개의 프로젝트를 모두 컴파일 해줌.

namespace myLibrary
{
    public class MyUtil
    {
        // 누구든지 외부에서 이 함수를 사용할 수 있도록, public으로 설정

        // 1. 값을 읽어들이고, int형으로 전환하는 함수 호출
        static public int GetDigit() // 전체 중 하나만 존재하며, 참조를 통해 공유되어 사용될 것이므로, static으로 설정
        {
            Console.WriteLine("값을 입력해 주세요. [0-100]");
            string val = Console.ReadLine(); // 무조건 string으로 받아와야 함.
            return ConvertStirngToInt(val); // -1은 에러
        }

        // 2. int형으로 전환하는 함수 실행 후, 반환
        static public int ConvertStirngToInt(string str)
        {
            int result = 0;

            bool ret = int.TryParse(str, out result);
            // TrytParse는 bool type으로 결과를 나타냄
            // str를 int형으로 바꿀 수 있다면, result라는 값에, str을 숫자로 바꿔서 넣어라.

            if (ret)
            {
                return result;
            }
            else
            {
                return -1; // 0-100 : 점수의 범위 , -1 : 에러(사용자 정의 규약)
            }
        }

    }
}

[ 디버그 수행 방법 ]

# 디버그(디버깅) 

프로그램의 오류를 발견하고 그 원인을 밝히는 작업 과정

아래와 같이 특정 부분을 지정한 후, 디버그 시작하면, 해당 부분부터 하나씩 디버그 수행

그러나 특정 부분을 지정하지 않고, 디버그를 시작하면, 처음부터 하나씩 디버그 수행

 

1. 디버그 수행 코드

- F5 : 디버그(에러추적) O / 실행(Run) O

- Ctrl + F5 : 디버그(에러추적) X / 실행(Run) O

 

2. 디버그 이동 코드

- F10키 : 다음 줄을 수행하며, 해당 함수로 이동해, 세부 코드를 모두 확인하지 않는다.

- F11키 : 코드를 하나씩 쫓아가며, 함수가 존재하면, 해당하는 함수 코드로 이동해 모든 과정을 확인할 수 있도록 돕는다.

 

3. 주의 사항

- 디버그를 수행할 프로젝트를 우클릭해, 시작 프로젝트 설정을 해야, 해당 프로젝트에서 디버그가 제대로 수행된다.

 


2. IF문 실습 2

1. 숫자를 받아들인다.

2. 숫자 범위가 0보다 작거나, 100보다 크면, 에러 처리를 한다.

3. 숫자가 91-100 사이이면, "A"를 출력한다.

4. 숫자가 81-90 사이이면, "B"를 출력한다.

5. 숫자가 71-80 사이이면, "C"를 출력한다.

6. 숫자가 61-70 사이이면, "D"를 출력한다.

7. 숫자가 60 이하이면, "F"를 출력한다.

 

1) if3 프로젝트 [ 콘솔 앱 (.NET Framework) ]

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if3
{
    class Program
    {
        static void Main(string[] args)
        {
            iftestMgr obj = new iftestMgr();
            obj.Run();
        }
    }
}

[ iftestMgr.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myLibrary;

namespace if3
{
    class iftestMgr
    {
        public void Run()
        {
            // EvalScore(MyUtil.GetDigit()); // 범위 체크가 없음.
            EvalScore(MyUtil.GetDigit(0, 100));
        }


        private void EvalScore(int digit)
        {
            if(digit == -2) {
                Console.WriteLine("0-100 사이의 값을 입력해주세요.");
                return;
            }
            else if(digit == -1) {
                Console.WriteLine("잘못 입력하셨습니다. 숫자를 입력해주세요.");
                return;
            }
            else if (digit > 90 && digit <= 100)
            {
                Console.WriteLine("A");
            }
            else if (digit > 80 && digit <= 90)
            {
                Console.WriteLine("B");
            }
            else if (digit > 70 && digit <= 80) 
            {
                Console.WriteLine("C");
            }
            else if(digit>60 && digit <= 70)
            {
                Console.WriteLine("D");
            }
            else if (digit <= 60)
            {
                Console.WriteLine("F");
            }
        }
    }
}

2) MyLibary 프로젝트 [ 클래스 라이브러리 (.net Framework) ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 클래스 라이브러리 (.net framework)
// 솔루션에서 우클릭 -> 솔루션 빌드를 하면, 이 3개의 프로젝트를 모두 컴파일 해줌.

namespace myLibrary
{
    public class MyUtil
    {

        /// <summary>
        /// 콘솔로부터 0 이상의 숫자를 받아들입니다.
        /// 만일 문자가 입력되면, -1이 반환됩니다.
        /// 숫자가 입력된 경우, int 형식으로 반환됩니다.
        /// </summary>
        /// <returns>int 숫자</returns>
        static public int GetDigit() // 전체 중 하나만 존재하며, 참조를 통해 공유되어 사용될 것이므로, static으로 설정
        {
            Console.WriteLine("값을 입력해 주세요. [0-100]");
            string val = Console.ReadLine(); // 무조건 string으로 받아와야 함.
            return ConvertStirngToInt(val); // val == -1은 에러
        }

        /// <summary>
        /// <para>콘솔로부터 0 이상의 숫자를 받아들입니다.
        /// 만일 문자가 입력되면, -1이 반환됩니다.
        /// 숫자가 입력된 경우, int 형식으로 반환됩니다.</para>
        /// 
        /// <para>이 함수는 주어진 min 값과, max값의 범위를 체크합니다.
        /// 만일 범위를 벗어나면, -2를 반환합니다.</para>
        /// </summary>
        /// <returns>int 숫자</returns>
        static public int GetDigit(int min, int max) // 전체 중 하나만 존재하며, 참조를 통해 공유되어 사용될 것이므로, static으로 설정
        {
            Console.WriteLine("값을 입력해 주세요. [0-100]");
            string val = Console.ReadLine(); // 무조건 string으로 받아와야 함.
            int iret = ConvertStirngToInt(val); // val == -1은 에러

            if (iret < 0){ return iret; }
            if (iret > max || iret < min) { return -2; } // 범위 오버
            return iret;

        }


        static public int ConvertStirngToInt(string str)
        {
            int result = 0;

            bool ret = int.TryParse(str, out result);
            // TrytParse는 bool type으로 결과를 나타냄
            // str를 int형으로 바꿀 수 있다면, result라는 값에, str을 숫자로 바꿔서 넣어라.

            if (ret)
            {
                return result;
            }
            else
            {
                return -1; // 0-100 : 점수의 범위 , -1 : 에러(사용자 정의 규약)
            }
        }

    }
}

 


3. IF문 실습 3

[ 성적 / 이름 / 성별을 입력 받는다. ]

1. 만일 남성이고, 성적이 90점 이상이면, "우수 장학생"을 출력

2. 만일 남성이고, 성적이 80점 이상이면, "장학생"을 출력

3. 만일 여성이고, 성적이 90점 이상이면, "해외연수 장학생"을 출력

4. 만일 여성이고, 성적이 80점 이상이면, "국비 장학생"을 출력한다.

5. 점수에 해당사항이 없으면, "해당 없음"을 출력한다.

6. 성별 구분은 Enum으로 구현하라.

 

1) if4 프로젝트

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if4
{
    class Program
    {
        static void Main(string[] args)
        {
            ScholarshipMgr s = new ScholarshipMgr();
            s.Run();
        }
    }
}

 

[ ScholarshipMgr.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myLibrary;

namespace if4
{
    class ScholarshipMgr
    {
        public void Run()
        {
            Scholarship scholar = new Scholarship(); // ex. 학생목록
            Student st = new Student(); // ex. 학생 n 생성
            st.ReadProperty(); // ex. 학생 n 속성 저장
            scholar.MyStudent = st; // ex. 학생 n 속성 값을, 학생목록에 저장
            scholar.EvaluateScolarShip(); // ex. 학생들의 속성 조건에 따라, 알맞는 결과값을 출력
        }

    }
}

 

[ Scholarship.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myLibrary;

namespace if4
{
    class Scholarship
    {
        public Student MyStudent { get; set; }// 학생 1 속성 저장값, 학생 2 속성 저장값, ... 생성

        // 1. 생성자
        public Scholarship(Student st) // 일을 한번에 끝낼 수 있는 과정
        {
            this.MyStudent = st; // 특정 Student의 속성 저장 인스턴스를, 저장한다. 즉 학생 n의 정보를 담아서, 전체 학생을 관리.
        }

        public Scholarship():this(null) { } // 자기자신 생성자 호출. Student st = null값을 줌.
        // 나중에 MyStudent 프로퍼티를 통해, 학생을 채워 넣어주겠다는 뜻


        // 2. 출력 메서드
        public void EvaluateScolarShip()
        {
            if(MyStudent == null) // 값이 채워지지 않고, 평가하라고 하고 있다면?
            {
                MyUtil.ErrorMessage("평가할 학생이 없습니다."); // 중요한 코드들 감춰둠.
                return;
            }

            if (MyStudent.Sex == SexEnum.남성)
            {
                if (IsError(MyStudent.Score)) { return; } 
                if(MyStudent.Score > 90) { MyUtil.PrintMessage("우수 장학생"); }
                else if (MyStudent.Score > 80) { MyUtil.PrintMessage("장학생");  }
                else { MyUtil.PrintMessage("해당사항 없음"); }
            }
            else if(MyStudent.Sex == SexEnum.여성)
            {
                if (IsError(MyStudent.Score)) { return; }
                if (MyStudent.Score > 90) { MyUtil.PrintMessage("해외연수 장학생"); }
                else if (MyStudent.Score > 80) { MyUtil.PrintMessage("국비 장학생"); }
                else { MyUtil.PrintMessage("해당사항 없음"); }
            }
            else{
                MyUtil.ErrorMessage("성 구분이 틀렸습니다."); return;
            }
        }


        // Score 오류 체크
        bool IsError(int value)
        {
            if (value == -2) { MyUtil.ErrorMessage("성적이 범위를 벗어났습니다. 다시 입력해주세요."); return true; }
            if (value == -1) { MyUtil.ErrorMessage("문자가 입력되었습니다. 숫자를 입력해주세요."); return true; }
            return false;
        }

    }
}

 

[ Student.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myLibrary;

namespace if4
{
    class Student
    {
        public string Name { get; set; }
        public int Score { get; set; }
        public SexEnum Sex { get; set; }


        public void ReadProperty()
        {
            // 함수명으로, 명확하게 기능을 알 수 있도록 해야함.
            Name = MyUtil.GetName();
            Score = MyUtil.GetDigit(0, 100); // 범위값 벗어남 : -2, 문자 : -1
            Sex = MyUtil.GetSex();
        }
    }
}

 


2) myLibrary 프로젝트

[ MyUtil.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myLibrary
{
    public class MyUtil
    {
        /// <summary>
        /// 콘솔로부터 0 이상의 숫자를 받아들입니다.
        /// 만일 문자가 입력되면, -1이 반환됩니다.
        /// 숫자가 입력된 경우, int 형식으로 반환됩니다.
        /// </summary>
        /// <returns>int 숫자</returns>
        static public int GetDigit() // 전체 중 하나만 존재하며, 참조를 통해 공유되어 사용될 것이므로, static으로 설정
        {
            Console.WriteLine("값을 입력해 주세요. [0-100]");
            string val = Console.ReadLine(); // 무조건 string으로 받아와야 함.
            return ConvertStringToInt(val); // val == -1은 에러
        }
            /// <summary>
            /// <para>콘솔로부터 0 이상의 숫자를 받아들입니다.
            /// 만일 문자가 입력되면, -1이 반환됩니다.
            /// 숫자가 입력된 경우, int 형식으로 반환됩니다.</para>
            /// 
            /// <para>이 함수는 주어진 min 값과, max값의 범위를 체크합니다.
            /// 만일 범위를 벗어나면, -2를 반환합니다.</para>
            /// </summary>
            /// <returns>int 숫자</returns>
        static public int GetDigit(int min, int max) // 전체 중 하나만 존재하며, 참조를 통해 공유되어 사용될 것이므로, static으로 설정
        {
            Console.WriteLine("성적을 입력하세요.");
            string val = Console.ReadLine(); // 무조건 string으로 받아와야 함.
            int iret = ConvertStringToInt(val); // val == -1은 에러

            if (iret < 0) { return iret; }
            if (iret > max || iret < min) { return -2; } // 범위 오버
            return iret;

        }

        /// <summary>
        /// 문자값을 숫자로 변환해서 반환합니다.
        /// 만일, 숫자가 아닌 문자가 포함된 경우, -1을 반환합니다.
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        static public int ConvertStringToInt(string str)
        {
            int result = 0;

            bool ret = int.TryParse(str, out result);
            // TrytParse는 bool type으로 결과를 나타냄
            // str를 int형으로 바꿀 수 있다면, result라는 값에, str을 숫자로 바꿔서 넣어라.

            if (ret)
            {
                return result;
            }
            else
            {
                return -1; // 0-100 : 점수의 범위 , -1 : 에러(사용자 정의 규약)
            }
        }

        static public SexEnum GetSex()
        {
            Console.WriteLine("성별을 입력하세요. [남성 = 1 입력 / 여성 = 2 입력]");
            string sex = Console.ReadLine();
            int isex = ConvertStringToInt(sex);

            if (isex == -1) { return SexEnum.오류; }
            else if (isex == 1) { return SexEnum.남성;  }
            else if (isex == 2) { return SexEnum.여성; }
            else { return SexEnum.오류;  }

        }

        static public string GetName()
        {
            SIJAK: // GOTO문 사용 방법
            Console.WriteLine("이름을 입력하세요.");
            string name = Console.ReadLine();

            // 이름에 아무것도 입력하지 않았을 경우 오류 처리 (즉 null 값 = "" 일 경우)
            if (string.IsNullOrEmpty(name))
            {
                Console.WriteLine("잘못 입력하셨습니다.");
                goto SIJAK;  // SIJAK부분으로 다시 이동해라
            }
            return name;
        }

        static public void ErrorMessage(string str)
        {
            Console.WriteLine(str);
        }
        static public void PrintMessage(string str)
        {
            Console.WriteLine(str);
        }
    }
}

 

[ enums.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myLibrary
{
    public enum SexEnum
    {
        남성 = 1, 여성 = 2, 오류 = 3
    }
}

 


3. Switch문 실습

위의 [if문 실습2]에서 성별 체크를, switch문으로 바꿔라.

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if5
{
    class Program
    {
        static void Main(string[] args)
        {
            ScRun obj = new ScRun();
            obj.Run();
        }
    }
}

[ ScRun.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace if5
{
    class ScRun
    {
        public void Run()
        {
            Scholarship scholar = new Scholarship(); // 인스턴스 생성
            scholar.MakeStudent(); // 인스턴스에 값 저장
        }
    }
}

[ Scholarship.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myLibrary;

namespace if5
{
    class Scholarship
    {
        // Student를 쓸 수 없지만, 학생 이름 / 성적 / 성별을 받아들이고, 이 학생을 처리해야 함.
        // 1. 따라서, 클래스 선언이 안되므로 변수 선언을 해야 함.
        
        // [ 문제 1 ] 아래와 같이 맴버 변수를 쓸 때의 문제 : 2^n(개수)만큼 복잡도가 증가한다.
        // 즉, 각각의 맴버 변수들을, 맴버 함수가 값을 변경시킬 수 있다. (개발자의 오류 발생 시, 조치 어려움 존재)
        string Name = null;
        SexEnum Sex;
        int Score;

        // [ 해결책 ] 이러한 문제들 때문에, 왠만하면 파라미터가 2개 이상 존재할 경우에는, 하나의 적절한 클래스를 만들어서 던져주는 위와 같은 방법이 효과적이다. => C스타일의 코딩을, OOP스타일의 코딩으로 변경시키자! 

        // 2. 생성자 - 각각의 값 받아들이기
        public Scholarship() 
        {
        }

        // 3. 인스턴스에 값 넣는 메서드
        public void MakeStudent() 
        {
            // [ 문제 2 ]아래와 같이, 지역 변수를 쓸 때의 문제 : 함수를 호출할 때마다 모든 파라미터를 사용해 호출해 줘야 한다.
            /*string Name = null;
            SexEnum Sex;
            int Score;*/

            Name = MyUtil.GetName();
            Sex = MyUtil.GetSex();
            Score = MyUtil.GetDigit();

            EvaluateScolarShip(Name, Sex, Score);
        }

        // 4. 출력 메서드
        public void EvaluateScolarShip(string name, SexEnum sex, int score)
        {
          
            switch (sex)
            {
                case SexEnum.남성 :
                    if (IsError(score)) { return; }
                    if (score > 90) { MyUtil.PrintMessage("우수 장학생"); }
                    else if (score > 80) { MyUtil.PrintMessage("장학생"); }
                    else { MyUtil.PrintMessage("해당사항 없음"); }
                    break;
                
                case SexEnum.여성 :
                    if (IsError(score)) { return; }
                    if (score > 90) { MyUtil.PrintMessage("해외연수 장학생"); }
                    else if (score > 80) { MyUtil.PrintMessage("국비 장학생"); }
                    else { MyUtil.PrintMessage("해당사항 없음"); }
                    break;
                
                default:
                    MyUtil.ErrorMessage("성 구분이 틀렸습니다."); 
                    break;
            }
        }


        // Score 오류 체크
        bool IsError(int value)
        {
            if (value == -2) { MyUtil.ErrorMessage("성적이 범위를 벗어났습니다. 다시 입력해주세요."); return true; }
            if (value == -1) { MyUtil.ErrorMessage("문자가 입력되었습니다. 숫자를 입력해주세요."); return true; }
            return false;
        }

    }
}

 

 


4. 반복문 실습 1

구구단을 출력하는 프로그램을 작성하시오.

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while3
{
    class Program
    {
        static void Main(string[] args)
        {
            WhileRun wr = new WhileRun();
            wr.Run();
        }
    }
}

[ WhileRun.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myLibrary;

namespace while3
{
    class WhileRun
    {
        public void Run()
        {
            TimesTable tt = new TimesTable();

            for (int i = 2; i < 10; i++)
            {
                tt.Base = i;
                tt.PrintBase();
                // TimesTable클래스를 쓰지 않고, 이중 for문을 돌려도 됨.
                // 그러나, 중첩된 for문은 풀어쓰면, 그냥 for문 2개로 풀어진다. 이런식으로 코딩을 할 수도 있음. => 프로그램을 간결하고 명확하게 인지할 수 있어야 함.
                Console.WriteLine("---------------------------------");
            }
        }
    }
}

[ TimesTable.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while3
{
    class TimesTable
    {
        public int Base { get; set; } // 몇 단

        public TimesTable(int iBase)
        {
            Base = iBase;
        }

        public TimesTable() : this(2) { }

        public void PrintBase()
        {
            for (int i = 1; i < 10; i++) // Base만 결정되면, 그 Base부터 9단까지 수행됨
            {
                Console.WriteLine($"{Base}*{i}={Base*i}");
            }
        }
    }
}

 


5. 반복문 실습 2

1부터 50까지의 숫자 중, 3의 배수만 출력하시오.

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while4
{
    class Program
    {
        static void Main(string[] args)
        {
            whileRun wr = new whileRun();
            wr.Run();
        }
    }
}

[ whileRun.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while4
{
    class whileRun
    {
        internal void Run()
        {
            ThreeDrainage td = new ThreeDrainage();

            for (int i = 1; i <= 50; i++)
            {
                td.PrintThreeDrainage(i);
            }
        }
    }
}

[ ThreeDrainage.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while4
{
    class ThreeDrainage
    {
        public int Base { get; set; }

        public ThreeDrainage(int iBase) 
        {
            Base = iBase;
        }
        public ThreeDrainage() : this(3) { }

        public void PrintThreeDrainage(int num)
        {
            if (num % 3 == 0)
            {
                Console.WriteLine(num);
            }
        }

    }
}

6. 반복문 실습 3

2019년 달력을 출력하시오.

- 요일 : 일,월,화,수,목,금,토

- 1월 1일은 일요일로 가정

- 2월은 28일까지

 

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while5
{
    class Program
    {
        static void Main(string[] args)
        {
            calendarMgr cm = new calendarMgr();
            cm.Run();
        }
    }
}

[ calendarMgr.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while5
{
    class calendarMgr
    {
        internal void Run()
        {
            calendar c = new calendar();
            c.PrintCalender();
        }
    }
}

[calendar.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while5
{
    class calendar
    {
        // 1. EndDate : 각 달 별로 끝나는 날짜 정의 (31, 30, 28)
        int[] Month31 = new int[] { 1, 3, 5, 7, 8, 10, 12 };
        int[] Month30 = new int[] { 4, 6, 9, 11 };

        // 3. 달력을 정확한 위치에 찍기 위함.
        int CurrentDay; 

        // 2, Month: 1월 - 12월
        public void PrintCalender()
        {
            for (int i = 1; i <= 12; i++)
            {
                PrintHeader(i);
                PrintMonth(i);
                PrintFooter();
            }
        }

        private void PrintHeader(int month)
        {
            Console.WriteLine($"[{month}월]");
            Console.WriteLine("--------------------------------------------------------");
            Console.WriteLine(string.Format("{0,-4}{1,-4}{2,-4}{3,-4}{4,-4}{5,-4}{6,-4}", "일", "월", "화", "수", "목", "금", "토")); // 좌측으로부터 맞춰서, 4칸 벌어지게 하기
        }


        public void PrintMonth(int month)
        {
            int endDate;
            if (Month31.Contains(month)) { endDate = 31; }
            else if (Month30.Contains(month)){ endDate = 30; }
            else { endDate = 28; }

            PrintSpace(); // CurrentDay 위치만큼, blank를 입력

            // month월을 출력한다.
            for (int i = 1; i <= endDate; i++)
            {
                PrintDate(i);
            }
        }

        private void PrintFooter()
        {
            Console.WriteLine();
            Console.WriteLine("--------------------------------------------------------");
            Console.WriteLine();
        }

        private void PrintSpace()
        {
            for (int i = 0; i < CurrentDay; i++)
            {
                Console.Write(string.Format("{0, -5:}", " "));
            }
        }

        public void PrintDate(int date)
        {
            Console.Write(string.Format("{0, -5:}", date));
            CurrentDay++;

            if (CurrentDay == 7)
            {
                CurrentDay = 0;
                Console.WriteLine();
            }
        }

    }

}


7. 반복문 실습 4

다음과 같이 별표를 출력하시오

[ Program.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while6
{
    class Program
    {
        static void Main(string[] args)
        {
            forMgr fg = new forMgr();
            fg.Run();
        }
    }
}

[ forMgr.cs ]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace while6
{
    class forMgr
    {
        public void Run()
        {
            Run1();
            Run2();
            Run3();
            Run4();
        }

     

        public void Run1()
        {
            for (int i = 1; i <= 5; i++)
            {
                // 메소드명만 보고도 직관적으로 기능을 이행할 수 있도록 해야 함.
                PrintStar1(i);
                PrintNewLine(); 
            }
        }

        // 메인 로직에, Console 등이 나타나는 것은 좋지 않음.
        void PrintStar1(int i)
        {
            // i는 1부터 5까지 연속된 값이 넘어온다.
            for (int j = 1; j <= i; j++)
            {
                Console.Write("*");
            }
        }


        public void Run2()
        {
            for (int i = 5; i >= 1; i--)
            {
                for (int j = i; j >= 1; j--)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
        }

        private void Run3()
        {
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= 5-i; j++)
                {
                    Console.Write(" ");
                }
                for (int j = 5-i; j < 5; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
        }

        private void Run4()
        {
            // blank : 4 - 3 - 2 - 1 - 0
            // * : 1 - 3 - 5 - 7 - 9
            // 2a + b = 9
            for (int i = 0; i < 5; i++) 
            {
                // 밖 i는 0,1,2,3,4로 돈다.
                // 그렇다면 이와 어떤 연관관계를 구성하는가
                PrintBlank4(i);
                PrintStar4(i);
                PrintBlank4(i);
                PrintNewLine();
            }

        }

        public void PrintBlank4(int i)
        {
            for (int j = 0; j < 4 - i; j++)
            {
                Console.Write(" ");
            }
        }
        public void PrintStar4(int i)
        {
            for (int j = 0; j < 2 * i + 1; j++)
            {
                Console.Write("*");
            }
        }


        void PrintNewLine()
        {
            Console.WriteLine();
        }
    }
}

* 유의사항
- 아직 공부하고 있는 문과생 코린이가, 정리해서 남겨놓은 정리 및 필기노트입니다.
- 정확하지 않거나, 틀린 점이 있을 수 있으니, 유의해서 봐주시면 감사하겠습니다.
- 혹시 잘못된 점을 발견하셨다면, 댓글로 친절하게 남겨주시면 감사하겠습니다 :)
반응형