C#/C# 교과서

[C# 교과서] 10~17. 연산자, if/else문, switch문, for문, while-do, foreach문, break/continue/goto 반복문 제어

서니션 2022. 12. 23. 14:05
728x90
반응형

TryParse() 메소드 특정 형식으로 변환이 가능하면 true를 반환

C# 7.0 버전 이후로는 out var 형식을 지원

if 문에 out var r 형식으로 r 변수를 직접 만들어 사용 할 수 있음


피보나치 수열 while문으로 표현

using System;

namespace codingstudy
{
    class Program
    {
        static void Main(string[] args)
        {
            int first = 0;
            int second = 1;

            while (second <= 20)
            {
                Console.WriteLine(second);
                int temp = first + second;
                first = second;
                second = temp;
            }
        }
    }
}

foreach문으로 배열 반복

foreach문 : 배열이나 컬렉션 같은 값을 여러 개 담고 있는 데이터 구조에서 각각의 데이터가 들어 있는 만큼 반복하는 반복문

반복 조건을 처리할 필요 없이 데이터가 있는 만큼 반복하는 구조

using System;

namespace codingstudy
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "ABC123";

            foreach (char c in str)
            {
                Console.Write($"{c}\\t");
            }
        }
    }
}

goto 구문

특정 레이블로 이동하는 기능

콜론(:) 기호를 레이블 이름 뒤에 붙여 만든다

using System;

namespace codingstudy
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("시작");
            Start:
            Console.WriteLine("0, 1, 2 중 하나 입력 : _\\b");
            int chapter = Convert.ToInt32(Console.ReadLine());

            if (chapter == 1)
            {
                goto Chapter1;
            }
            else if (chapter == 2)
            {
                goto Chapter2;
            }
            else
            {
                goto End;
            }

            Chapter1:
            Console.WriteLine("1장");

            Chapter2:
            Console.WriteLine("2장");

            goto Start;

            End:
            Console.WriteLine("종료");
        }
    }
}
728x90
반응형