본문 바로가기
전공/C# 프로그래밍

5강. 코드 흐름 제어

by 임 낭 만 2023. 4. 16.

흐름 제어 (Flow of Control) : 코드 실행 순서를 결정하는 것

분기문

프로그램의 흐름을 조건에 따라 변화시키는 구문 (제어 흐름을 여러 갈래로 나누는 것) : if문, switch

단 프로그램은 한 번에 하나의 갈래만 실행할 수 있다.

if문 : 한 번에 단 하나의 조건을 평가함. / swirch문 : 조건식의 다양한 결과를 한 번에 평가 후 프로그램의 흐름을 나눌 때 사용

if 문

  • 프로그램의 흐름을 조건에 따라 여러 갈래로 나누는 구문
  • if ~ else if ~ else 조건문
    • if 문에서 사용하는 조건식은 true 또는 false의 값을 가지는 bool 형식

조건을 만족하는 경우에만 분기 수행. else if 절과 else 절은 옵션

using System;

namespace IfElse
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("숫자를 입력하세요. : ");

            string input = Console.ReadLine();
            int number = Int32.Parse(input);

            if (number < 0)
                Console.WriteLine("음수");
            else if (number > 0)
                Console.WriteLine("양수");
            else
                Console.WriteLine("0");

            if (number % 2 == 0)
                Console.WriteLine("짝수");
            else
                Console.WriteLine("홀수");
        }
    }
}

using System;

namespace IfIf
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("숫자를 입력하세요. : ");

            string input = Console.ReadLine();
            int number = Int32.Parse(input);

            if (number > 0)
            {
                if (number % 2 == 0)
                    Console.WriteLine("0보다 큰 짝수");
                else
                    Console.WriteLine("0보다 큰 홀수");
            }
            else
            {
                Console.WriteLine("0보다 작거나 같은 수.");
            }
        }
    }
}

switch 문

  • 조건식의 결과가 가질 수 있는 다양한 경우를 평가
    • C언어와 달리 조건식에서 정수 뿐 아니라 문자열 형식 지원
  • break 문
    • 프로그램 흐름을 멈추고 현재 실행 중인 코드의 바깥으로 실행 위치를 옮김
    • goto 또는 return과 같은 점프문을 대신하여 사용 가능

입력식 / 값이 어떤 사례 (case)와 매치되는지를 평가하여 분기 수행. 분기 수행 후엔 break문을 이용하여 switch문 탈출

using System;

namespace Switch
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("요일을 입력하세요.(일,월,화,수,목,금,토) : ");
            string day = Console.ReadLine();

            switch (day)
            {
                case "일":
                    Console.WriteLine("Sunday");
                    break;
                case "월":
                    Console.WriteLine("Monday");
                    break;
                case "화":
                    Console.WriteLine("Tuesday");
                    break;
                case "수":
                    Console.WriteLine("Wednesday");
                    break;
                case "목":
                    Console.WriteLine("Thursday");
                    break;
                case "금":
                    Console.WriteLine("Friday");
                    break;
                case "토":
                    Console.WriteLine("Saturday");
                    break;
                default:
                    Console.WriteLine($"{day}는 확인불가.");
                    break;
            }            
        }
    }
}

 

데이터 형식 따라 분기하는 switch 문

  • C# 7.0 부터 switch 문에 데이터 형식을 조건으로 사용
    • case 절에 데이터 형식 옆에 식별자 반드시 포함

C# 컴파일러는 123 리터럴을 평가하여 int 형식임을 유추함. 그리고 obj 안에 박싱해 넣음. obj에 담겨져 있는 데이터 형식이 int이므로 프로그램은 이 case 절을 따라 분기함.

  • TryParse ()
    • 모든 숫자형식에서 포함하는 메서드
    • 문자열을 숫자형식 데이터로 변환
    • 변환 성공 시 true 반환, 실패 시 false 반환
    • out 키워드를 통한 출력 전용 매개변수 사용
using System;
using System.ComponentModel;

namespace Switch2
{
    class Program
    {
        static void Main(string[] args)
        {
            object obj = null;
            
            string s = Console.ReadLine();
            if (int.TryParse(s, out int out_i))
                obj = out_i;
            else if (float.TryParse(s, out float out_f))
                obj = out_f;
            else
                obj = s;

            switch (obj)
            {
                case int i:
                    Console.WriteLine($"{i}는 int 형식.");
                    break;
                case float f when f >= 0:
                    Console.WriteLine($"{f}는 float 형식.");
                    break;
                default:
                    Console.WriteLine($"{obj}는 모르는 형식.");
                    break;
            }
        }
    }
}

추가 조건 검사를 위한 when 절

switch 식

  • switch 문과 switch 식과의 차이
    • switch 문은 어떤 작업에 분기가 필요 할 때 사용하고, switch 식은 분기를 거쳐 결과 값을 내놓아야 할 때 사용
  • switch 문에서 switch 식으로 변환
    • 조건식을 switch 키워드 앞으로 위치
    • case 키워드와 “:” 대신에 “=>” 사용
    • “break;” 대신에 콤마(,) 사용
    • default 키워드 대신에 “_” 사용
    • 세미콜론 “;”으로 종료

using System;
using System.Runtime.InteropServices;

namespace SwitchExp
{
    class Program
    {
        static void Main(string[] args)
        {
            int input = Convert.ToInt32(Console.ReadLine());

            // 1의 자리를 버림
            int score = (int)(Math.Truncate(input / 10.0)) * 10;
            string grade = "";

            bool repeated = true;

            switch (score)
            {
                case 90:
                    grade = "A";
                    break;
                case 80 when repeated == true:
                    grade = "B+";
                    break;
                case 80:
                    grade = "B";
                    break;
                case 70:
                    grade = "C";
                    break;
                case 60:
                    grade = "D";
                    break;
                default:
                    grade = "F";
                    break;
            }

            string grade2 = score switch
            {
                90 => "A",
                80 when repeated == true => "B+",
                80 => "B",
                70 => "C",
                _ => "F"
            };

            Console.WriteLine($"grade: {grade}, grade2: {grade2}");
        }
    }
}

 

using System;

namespace SwitchExp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("점수를 입력하세요");
            int score = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("재수강인가요? (y/n)");
            string line = Console.ReadLine();
            bool repeated = line == "y" ? true : false;

            string grade = (int)(Math.Truncate(score/10.0)*10) switch
            {
                90 when repeated == true => "B+",
                90 => "A",                
                80 => "B",
                70 => "C",
                60 => "D",
                _ => "F"
            };
            Console.WriteLine($"학점 : {grade}");
        }
    }
}


반복문 (Loop Statement)

루프문, 특정 조건을 만족하는 동안 코드 (블록)을 반복 실행

while, do while, for, foreach

while 문, do while 문

  • while 문
    • 조건식이 참인 동안 코드를 반복 실행

조건식 - 논리 형식

  • do while 문
    • 처음 한번은 코드를 실행 후, 조건식이 참인 동안 코드를 반복 실행

무조건 한 번의 실행을 보장하는 반복문

using System;

namespace While
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 10;
            while (i > 0)
            {
                Console.WriteLine("a) i : {0}", i--);                
            }

            do
            {
                Console.WriteLine("b) i : {0}", i--);
            }
            while (i > 0);
        }
    }
}

for 문

  • 조건식이 참인 동안 코드를 반복 실행
  • while 문 보다 반복을 더 정교하게 제어
  • 초기화식
    • 반복을 실행하기 전에 최초에 한 번 실행하는 코드로써 보통 변수 초기화 수행
  • 조건식
    • 반복을 계속 수행할지를 결정
  • 반복식
    • 반복이 끝날 때마다 실행, 주로 조건식에서 사용되는 변수 값 조정

1. 조건변수 초기화 2. 조건 비교 3. 조건변수 증/감

using System;

namespace ForFor
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i=0; i<5; i++)
            {
                for (int j = 0; j <= i; j++)
                {
                    Console.Write("*");
                }
                Console.WriteLine();
            }
        }
    }
}

중첩 반복

+++) for문과 while문의 무한 반복 코드

for ( ; ; )
	//반복 실행할 코드 블록
    
while ( true )
	//반복 실행할 코드 블록

foreach 문

  • 배열 (또는 컬렉션)을 순회하면 각 데이터 요소에 차례로 접근
  • 배열 (또는 컬렉션) 끝에 도달하면 자동으로 반복이 종료
  • “in” 키워드와 함께 사용
    • 배열의 각 요소를 순회하면서 in 키워드 앞에 있는 변수에 할당

  • 배열
    • 여러 개의 데이터를 담을 수 있는 코드 요소

배열과 컬렉션 (foreach문 추가)

배열이나 컬렉션에 주로 사용함
배열 - 여러 개의 데이터를 담는 코드 요소 / 컬렉션 - 배열과 비슷하나 데이터 저장 및 액세스 방식이 다름

배열이나 컬렉션을 순회하며 각 데이터 요소에 접근 가능


점프문

: 실행 흐름을 끊거나 실행 위치를 원하는 곳으로 이동 (break, continue, goto, return, throw) 흐름을 특정 위치로 단번에 이동

break 문

  • 현재 실행 중인 반복문이나 switch 문의 실행을 중단하고자 할 때 사용
using System;

namespace Break
{
    class Program
    {
        static void Main(string[] args)
        {
            while(true)
            {
                Console.Write("계속할까요?(예/아니오) : ");
                string answer = Console.ReadLine();

                if (answer == "아니오")
                    break;
            }            
        }
    }
}

continue 문

  • 반복문에서 한 회 코드블록 실행을 건너 뛰어 반복을 계속 수행
    • continue 문을 만나면 코 드블록 안에서 그 아래 코드 자동 실행 취소
    • 가독성이 좋은 특징을 가짐
using System;

namespace Continue
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i =0; i<10; i++)
            {
                if (i % 2 == 0)
                    continue;

                Console.WriteLine($"{i} : 홀수");
            }
        }
    }
}

goto 문

  • 코드 안에 레이블을 정의 goto 문을 만나면 바로 레이블로 이동
    • 중첩된 반복문을 지정한 레이블 위치로 단숨에 빠져나올 수 있는 장점
    • 가독성이 안 좋게 만드는 단점 (실행 흐름을 복잡하게 만듦)

댓글