2014년 2월 20일 목요일

7.C#제어문, 반목문(for, while, foreach, if, switch), C#/WPF/닷넷WPF/ASP.NET/ADO닷넷/닷넷교육/닷넷강좌학원/닷넷공부/닷넷책/닷넷객체지향교육

7.C#제어문, 반목문(for, while, foreach, if, switch), C#/WPF/닷넷WPF/ASP.NET/ADO닷넷/닷넷교육/닷넷강좌학원/닷넷공부/닷넷책/닷넷객체지향교육

이번 강좌에서는 제어문 또는 명령문에 대해 살펴 봅니다.
<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
선택을 위한 if, switch 문
1. if문 

if statement : 어떤 조건의 참, 거짓을 판단하여 실행을 제어하는 구조에 사용. 


condition 부분의 결과값은 반드시 true또는 false가 되어야 한다.
(No implicit conversion from int to bool ) 
다른 언어들의 경우: 0 이나 -1을 false로 나머지를 true로 암시적 형 변환 

int x; 
… 
if(x) …//must be if (x!=0) in c# 
if(x=0) …//must be if (x==0) in c# 

[예] 


enum Suit { Clubs , Hearts , Diamonds , Spades }; 

Suit trumps = Suit.Hearts; 
if ( trumps == Suit.Clubs ) 
color = "Black"; 
else if ( trumps == Suit.Hearts ) 
color = "Red"; 
else if ( trumps == Suit.Diamonds ) 
color = "Red"; 
else 
color ="Black"; 



2. switch 문 


switch문의 변수 값과 일치하는 case로 분기. (진입점) 

변수값이 일치하는 case가 없을 경우 default로 분기. 
break
문을 만나면 switch문 외부로 분기 (종단점) 

[예] 


switch(trumps) { 
case Suit.Clubs: 
case Suit.Spades: 
color = "Black" ; break; 
case Suit.Hearts: 
case Suit.Diamonds: 
color = "Red" ; break; 
default: 
color = "ERROR"; break; 

} 

다음은 반복문 입니다. (while, do~while, for, foreach) 

1. while문 

형식: 

while (condition) 
{ 
statements; 
} 
조건이 참인 동안에 statement를 실행 합니다. 

[예] 

<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
//1부터 100까지 수중 홀수 출력
static void Main(string[] args)
        {
            int i = 0;
            while (i < 100)
            {
                i += 1;
                if (i % 2 != 0)
                    Console.WriteLine("while:{0}", i);
            }
                        
        }

2.do~while문 

형식 : 

do{ 
statements; 
} while (condition); 


while문과의 차이는 조건에 맞지 않더라도 statement를 한번은 수행하는 구조 입니다. 그러나 while문에서는 조건에 맞지 않으면 statement를 한번도 수행 하지 않을수도 있습니다. 


[예] 

<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
//1부터 100까지 수중 홀수 출력
static void Main(string[] args)
        {
            int i = 0;
            do
            { i+=1;
              if (i % 2 != 0)
              Console.WriteLine("dowhile:{0}", i);
            }
            while (i<100);
         }

3. for문 

형식: 

for(초기치; 조건; 업데이트 실행){ 

statements; 
} 
일반적인 for문과 같으므로 별다른 설명은 하지 않겠습니다. 

[예] 

<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->
//1부터 100까지 수중 홀수 출력
static void Main(string[] args)
        {
          
            for (int i = 1; i <= 100; i++)
           
                if (i % 2 != 0)
                                
            Console.WriteLine("for:{0}", i);
                              
        }



4. foreach문 

형식: 

foreach(item in 배열 또는 컬렉션){ 

statements; 
} 
배열: 여러 개의 데이터를 하나의 변수 또는 객체에 담아두는 것 
컬렉션: 자유로운 형태로 여러 개의 데이터를 담아둘 수 있습니다. ArrayList, HashTable, Icollection 등이 있습니다. 
실행순서를 설명 드리면 배열이나 컬렉션에서 하나의 항목을 읽은 후 statement를 수행하고 다음 foreach로 가서 다음 읽을것이 있으면 다시 읽고 statement를 실행하는 순서로 동작 합니다. 만약 다음 읽을것이 없다면 루프를 빠져 나옵니다. 

[예] 

<!--[if !supportLineBreakNewLine]-->
<!--[endif]-->

using System;
using System.Collections.Generic;
using System.Text;
namespace Ex15
{
    //
사용자가 만드는 모든 배열은 기본적으로 Array 클래스를 상속합니다.
    //
배열도 객체다.
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[2];
            int[] arr2 = new int[2] { 10, 20 };
            int[] arr3 = new int[] { 10, 20 };
            int[] arr4 = { 10, 20 };
            for (int i = 0; i < 2; i++)
            {
                Console.WriteLine(arr4[i]);
            }

            for (int i = 0; i < arr3.Length; i++)
            {
                Console.WriteLine(arr3[i]);
            }

            foreach (int i in arr2)
            {
                Console.WriteLine(i);
            }
        }
    }
}


이번에는 제어를 조절할 수 있는 break,continue에 대해 알아 보겠습니다. 

break : 반복문 내의 임의의 지점에서 루프를 빠져나가야 할 때 break문을 사용 합니다. 싸고 있는 루프중 가장 가까운 루프를 빠져 나간다. 

continue : 루프의 남은 부분을 skip하고 루프의 처음으로 제어를 옮긴다.


[반복문 예제]


1. 10진수를 이진수로 바꾸는 프로그램(10진수를 2로 계속 나누어 나머지를 뒤에서 부터 붙이면 이진수로 바뀜)

static void Main(string[] args)
        {
            int[] note = new int[10];
            int i;

            string data = "";
       
            Console.Write("10진수를 2진수로: ");

            int n = int.Parse(Console.ReadLine());

            for (i = 0; i < i + 1; i++)
            {
                if (n > 1)
                {
                    note[i] = n % 2;
                    data = note[i].ToString() + data;
                    n /= 2;
                }
                else
                {
                    note[i] = n;
                    break;
                }
            }
           Console.WriteLine("2진수: " + data);
           Console.ReadLine();
        }
    }
}




static void Main(string[] args)
        {
            int[] note = new int[10];
            int i;

            string data = "";
       
            Console.Write("10진수를 2진수로: ");

            int n = int.Parse(Console.ReadLine());
            i = 0;
            while (i < i + 1)
            {
                if (n > 1)
                {
                    note[i] = n % 2;
                    data = note[i].ToString() + data;
                    n /= 2;
                    i++;
                }
                else
                {
                    note[i] = n;
                    break;
                }
            }
           Console.WriteLine("2진수: " + data);
           Console.ReadLine();
        }
    }
}





        static void Main(string[] args)
        {
            int[] note = new int[10];
            int i;

            string data = "";
       
            Console.Write("10진수를 2진수로: ");

            int n = int.Parse(Console.ReadLine());
            i = 0;
            do
            {
                if (n > 1)
                {
                    note[i] = n % 2;
                    data = note[i].ToString() + data;
                    n /= 2;
                    i++;
                }
                else
                {
                    note[i] = n;
                    break;
                }
            } while (i < i + 1);
           Console.WriteLine("2진수: " + data);
           Console.ReadLine();
        }
    }
}



2. 정수값을 입력하면 그 수까지의 팩토리얼을 구하는 프로그램
(C# Main함수에서 정수 값을 입력 받도록 구성)


static void Main(string[] args)
        {
            Console.WriteLine("계산하고 싶은 팩토리얼 수를 입력하세요.");
            string inputnum = Console.ReadLine();
            int result = 1;
            for(int i=1; i<=Int32.Parse(inputnum); i++)
                        {
                            result *= i;
            }
            Console.WriteLine("팩토리얼 값: {0}", result);
            
            result = 1;
            int j = 1;
            while (j <= Int32.Parse(inputnum))
            {
                result *= j;
                j++;
            }
            Console.WriteLine("팩토리얼 값: {0}", result);
            result = 1;
            int k = 1;
            do
            {
                result *= k;
                
                k++;
            }
            while (k <= Int32.Parse(inputnum));
            Console.WriteLine("팩토리얼 값: {0}", result);
          }



3. 1부터 100까지 수중 소수를 출력 하는 프로그램(소수는 1과 자기가신이외에는 나누어 떨어지지 않는 수)


static void Main(string[] args)
        {
            int i, j;
            int count = 0;
            int sosu = 0;
            
            for (i = 2; i <= 100; i++)
            {
                j = i;
                for (int k = 1; k < j + 1; k++)
                {
                   
                    if (j % k == 0)
                        count = count + 1;

                }
                if (count <= 2)
                {
                    Console.WriteLine("for를 이용한 소수 구하기:{0} ", j);
                    sosu++;
                }
                count = 0;
            }
            Console.WriteLine(count);


            i = 1;
            j = 1;
            count = 0;
            sosu = 0;
            while(i<100)
            {
                i++;
                j = i;
                for (int k = 1; k < j + 1; k++)
                {

                    if (j % k == 0)
                        count = count + 1;

                }
                if (count <= 2)
                {
                    Console.WriteLine("while을 이용한 소수 구하기:{0} ", j);
                    sosu++;
                }
                count = 0;
            }
            Console.WriteLine(count);

            i = 1;
            j = 1;
            count = 0;
            sosu = 0;
            do
            {
                i++;
                j = i;
                for (int k = 1; k < j + 1; k++)
                {

                    if (j % k == 0)
                        count = count + 1;

                }
                if (count <= 2)
                {
                    Console.WriteLine("dowhile을 이용한 소수 구하기:{0} ", j);
                    sosu++;
                }
                count = 0;
            }
            while (i < 100);
            Console.WriteLine(count);
            
        }
    }
}
 

댓글 없음:

댓글 쓰기