C#

continue/break/멤버변수/지역변수

s0002 2023. 1. 8. 13:54

반복문에서 continue와 break 사용

using System;

namespace Study01
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                int j = i + 1;    //1, 2, 3

                if (j % 2 == 0)
                    continue; //가장 가까운 반복문 새로 시작 (j가 짝수이면 넘어감)

                else if (j >= 3)
                    break; //가장 가까운 반복문 종료(j가 3이 되면 종료)

                Console.WriteLine(j); //3보다 작은 홀수 출력
            }
        }
    }
}

멤버변수와 지역변수

using System;

namespace Review
{
    class Program
    {
        static void Main(string[] args)
        {
            App app= new App();

            Console.WriteLine(app.num1); //num1의 초기값 0 출력

            Console.WriteLine(app.Add(5));
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace Review
{
    class App
    {
        //멤버변수
        //멤버변수 선언 후 값을 할당하지 않아도 오류 안남
        //해당 데이터 타입의 기본값(0) 들어가 있음
        //메서드에서(메서드에서 선언한 지역변수의 값은 메서드가 끝나면 사라지므로)
        //선언한 지역변수의 값을 저장할 때 자주 사용한다
        public int num1; 

        //생성자
        public App()
        {
            Console.WriteLine("App 생성");
        }

        //멤버 메서드
        public int Add(int num2) //멤버변수 num1과 매개변수 num2를 더한다
        {          
            this.num1 = this.num1 + num2;

            //지역변수
            int result;
            result = this.num1; //지역변수 선언 후 값을 할당해 줘야 사용 가능

            return result;
        }
    }
}