본문으로 이동

C 샤프 프로그래밍/제어문

위키책, 위키책

조건문, 반복문, 분기문 그리고 예외 처리 구문은 실행 프로그램의 흐름을 제어할 수 있다.

선택문은 if, 그리고switch와 같은 키워드를 사용하여 참과 거짓을 통하여 수행 구문을 결정할 수 있다.

반복문은 do, while, for, foreach, 그리고 in과 같은 키워드를 사용하여 루프를 생성할 수 있다.

분기문은 break, continue, return, 그리고yield와 같은 키워드를 사용하여 프로그램 제어를 전송하는데 사용할 수 있다.

조건문

[+/-]

조건문은 조건에 따라 실행할 구문을 결정한다. C# 에서 조건문의 형태는 if문과 switch 문, 두 개가 존재한다.

if

[+/-]

C#의 대부분과 같이 if 구문도 C, C++, 그리고 Java 에서와 같은 문법을 가진다. 따라서 다음의 형태와 같이 작성한다:

if-구문 ::= "if" "(" 조건식 ")" if-본문 ["else" else-본문]
조건식 ::= 불리언-형식
if-본문 ::= 구문-또는-구문-구간
else-본문 ::= 구문-또는-구문-구간

if 구문은 if-본문이 실행여부를 결정하기 위하여 조건식을 평가한다. 부가적으로 else절은 조건식false일 경우 실행되는 구문 입니다. else-bodyif, else if, else if, else if, else 구문으로 계단식 if 구문을 생성할 수 있다:

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;
        if ( myNumber == 4 )
            Console.WriteLine("myNumber가 4가 아니기 때문에 이것은 보이지 않습니다.");
        else if( myNumber < 0 )
        {
            Console.WriteLine("myNumber가 음수가 아니기 때문에 이것은 보이지 않습니다.");
        }
        else if( myNumber % 2 == 0 )
            Console.WriteLine("myNumber가 짝수가 아니기 때문에 이것은 보이지 않습니다.");
        else
        {
            Console.WriteLine("myNumber가 조건문들과 일치하지 않기 때문에 이 문장이 보여지게 됩니다!");
        }
    }
}

switch

[+/-]

The switch statement is similar to the statement from C, C++ and Java.

Unlike C, each case statement must finish with a jump statement (which can be break or goto or return). In other words, C# does not support "fall through" from one case statement to the next (thereby eliminating a common source of unexpected behaviour in C programs). However "stacking" of cases is allowed, as in the example below. If goto is used, it may refer to a case label or the default case (e.g. goto case 0 or goto default).

The default label is optional. If no default case is defined, then the default behaviour is to do nothing.

A simple example:

switch (nCPU)
{
    case 0:
         Console.WriteLine("You don't have a CPU! :-)");
         break;
    case 1:
         Console.WriteLine("Single processor computer");
         break;
    case 2:
         Console.WriteLine("Dual processor computer");
         break;
    // Stacked cases
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
         Console.WriteLine("A multi processor computer");
         break;
    default:
         Console.WriteLine("A seriously parallel computer");
         break;
}

A nice improvement over the C switch statement is that the switch variable can be a string. For example:

switch (aircraft_ident)
{
    case "C-FESO":
         Console.WriteLine("Rans S6S Coyote");
         break;
    case "C-GJIS":
         Console.WriteLine("Rans S12XL Airaile");
         break;
    default:
         Console.WriteLine("Unknown aircraft");
         break;
}

반복문

[+/-]

An iteration statement creates a loop of code to execute a variable number of times. The for loop, the do loop, the while loop, and the foreach loop are the iteration statements in C#.

do...while

[+/-]

The do...while loop likewise has the same syntax as in other languages derived from C. It is written in the following form:

do...while-loop ::= "do" body "while" "(" condition ")"
condition ::= boolean-expression
body ::= statement-or-statement-block

The do...while loop always runs its body once. After its first run, it evaluates its condition to determine whether to run its body again. If the condition is true, the body executes. If the condition evaluates to true again after the body has ran, the body executes again. When the condition evaluates to false, the do...while loop ends.

using System;

public class DoWhileLoopSample
{
    public void PrintValuesFromZeroToTen()
    {
         int number = 0;
         do
         {
              Console.WriteLine(number++.ToString());
         } while(number <= 10);
    }
}

The above code writes the integers from 0 to 10 to the console.

for

[+/-]

The for loop likewise has the same syntax as in other languages derived from C. It is written in the following form:

for-loop ::= "for" "(" initialization ";" condition ";" iteration ")" body
initialization ::= variable-declaration | list-of-statements
condition ::= boolean-expression
iteration ::= list-of-statements
body ::= statement-or-statement-block

The initialization variable declaration or statements are executed the first time through the for loop, typically to declare and initialize an index variable. The condition expression is evaluated before each pass through the body to determine whether to execute the body. It is often used to test an index variable against some limit. If the condition evaluates to true, the body is executed. The iteration statements are executed after each pass through the body, typically to increment or decrement an index variable.

public class ForLoopSample
{
    public void ForFirst100NaturalNumbers()
    {
        for(int i=0; i<100; i++)
        {
            System.Console.WriteLine(i.ToString());
        }
    }
}

The above code writes the integers from 0 to 99 to the console.

foreach

[+/-]

The foreach statement is similar to the for statement in that both allow code to iterate over the items of collections, but the foreach statement lacks an iteration index, so it works even with collections that lack indices altogether. It is written in the following form:

foreach-loop ::= "foreach" "(" variable-declaration "in" enumerable-expression ")" body
body ::= statement-or-statement-block

The enumerable-expression is an expression of a type that implements IEnumerable, so it can be an array or a collection. The variable-declaration declares a variable that will be set to the successive elements of the enumerable-expression for each pass through the body. The foreach loop exits when there are no more elements of the enumerable-expression to assign to the variable of the variable-declaration.

public class ForEachSample
{
    public void DoSomethingForEachItem()
    {
        string[] itemsToWrite = {"Alpha", "Bravo", "Charlie"};
        foreach (string item in itemsToWrite)
            System.Console.WriteLine(item);
    }
}

In the above code, the foreach statement iterates over the elements of the string array to write "Alpha", "Bravo", and "Charlie" to the console.

while

[+/-]

The while loop has the same syntax as in other languages derived from C. It is written in the following form:

while-loop ::= "while" "(" condition ")" body
condition ::= boolean-expression
body ::= statement-or-statement-block

The while loop evaluates its condition to determine whether to run its body. If the condition is true, the body executes. If the condition then evaluates to true again, the body executes again. When the condition evaluates to false, the while loop ends.

using System;

public class WhileLoopSample
{
    public void RunForAwhile()
    {
        TimeSpan durationToRun = new TimeSpan(0, 0, 30);
        DateTime start = DateTime.Now;
        while (DateTime.Now - start < durationToRun)
        {
            Console.WriteLine("not finished yet");
        }
        Console.WriteLine("finished");
    }
}

분기문

[+/-]

A jump statement can be used to transfer program control using keywords such as break, continue, return, yield, and throw.

break

[+/-]

A break statement is used to exit from a case in a switch statement and also used to exit from for, foreach,while, do.....while loops which will switch the control to the statement immediately after the end of the loop.

continue

[+/-]

The continue keyword transfers program control just before the end of a loop. The condition for the loop is then checked, and if it is met, the loop performs another iteration.

return

[+/-]

The return keyword identifies the return value for the function or method (if any), and transfers control to the end of the function.

yield

[+/-]

The yield keyword is used to define an iterator block which produces values for an enumerator. It is typically used within a method implementation of the IEnumerable interface as an easy way to create an iterator. It is written in the following forms:

yield ::= "yield" "return" expression
yield ::= "yield" "break"

The following example shows the usage of the yield keyword inside the method MyCounter. This method defines an iterator block, and will return an enumerator object which generates the value of a counter from zero to stop, incrementing by step for each value generated.

using System;
using System.Collections;

public class YieldSample
{
    public IEnumerable MyCounter(int stop, int step)
    {
        int i;
        for (i = 0; i < stop; i += step)
        {
            yield return i;
        }
    }

   static void Main()
   {
       foreach (int j in MyCounter(10, 2))
       {
           Console.WriteLine("{0} ", j);
       }
       // will display 0 2 4 6 8
   }
}

throw

[+/-]

The throw keyword throws an exception. If it is located within a try block, it will transfer the control to a catch block that matches the exception - otherwise, it will check if any calling functions are contained within the matching catch block and transfer execution there. If no functions contain a catch block, the program may terminate because of an unhandled exception.

Exceptions and the throw statement are described in greater detail in the Exceptions chapter.