본문 바로가기
C#(CSharp)/기초강좌(Basic)

[7] C# 조건문 (C# if else statement)

by swconsulting 2015. 2. 23.

프로그램 개발 할때 가장 많이 사용하면서 중요한 개념인 if else 구문에 대해서 알아 보겠습니다.


(1) if else 문법





 

위 그림에서 처럼 조건값이 True이면 if {}를 수행하고 False이면 else{} 를 수행하는 것입니다.

프로그래머 4자 성어이 백문이 불여 일타인 아래 샘플 코드를 보면 이해가 좀더 쉬울 것입니다.


<Sample code>

void If_Else_Sample()

        {

            // local variable definition

            int a = 100;

            // check the boolean condition

            if (a < 20)

            {

                // if condition is true then print the following

                Console.WriteLine("a is less than 20");

            }

            else

            {

                // if condition is false then print the following

                Console.WriteLine("a is not less than 20");

            }

            

            Console.WriteLine("value of a is : {0}", a);

        }

[출력]

a is not less than 20;

 

value of a is : 100


(2) switch case 구문

if 처럼 아래 flow chart 이미지를 보면 좀 더 쉽게 이해가 될 것입니다.

switch와 if는 동작 구조는 동일합니다. 하지만, break를 이용해서 구문이 빠져 나가는 것입니다.


 


<Sample Code>

void Switch_Case_Sample()

        {           

            char grade = 'B'

 

            switch (grade)            

            {                 

                case 'A':                    

                    Console.WriteLine("Excellent!");                    

                    break;

                case 'B'

                case 'C':   

                    Console.WriteLine("Well done");   

                    break;                

                case 'D':                  

                    Console.WriteLine("You passed");   

                    break;                

                case 'F':       

                    Console.WriteLine("Better try again");    

                    break;               

                default:            

                    Console.WriteLine("Invalid grade");

                    break;            

            }             

 

            Console.WriteLine("Your grade is  {0}", grade);   

        }

 

<출력>

Well done

 

Your grade is B



참고 : http://www.tutorialspoint.com/csharp/index.htm