05
26

1) 복합 대입 연산자(compound assignment operator)

연산자 평가 방식 예제
+= 우측 피연산자의 값을 좌측 피연산자 값에 더해 그 결과를 좌측 피연산자에 대입한다. int n = 50;
n += 5; // 결괏값 55
// n = n + 5;
-= 우측 피연산자의 값을 좌측 피연산자 값에서 빼고 그 결과를 좌측 피연산자에 대입한다. int n = 50;
n -= 5; // 결괏값 45
// n = n - 5;
*= 우측 피연산자의 값을 좌측 피연산자 값에 곱해 그 결과를 좌측 피연산자에 대입한다. int n = 50;
n *= 5; // 결괏값 250
// n = n * 5;
/= 우측 피연산자의 값으로 좌측 피연산자 값을 나눠 그 결과를 좌측 피연산자에 대입한다. int n = 50;
n /= 5; // 결괏값 10
// n = n / 5;
%= 우측 피연산자의 값으로 좌측 피연산자 값의 나머지 값을 구하고 그 결과를 좌측 피연산자에 대입한다. int n = 50;
n %= 5; // 결괏값 0
// n = n % 5;

 

cf. Convert

문자열과 수치는 C#에서 내부적인 포맷이 완전히 다르기 때문에 캐스팅 연산자와 같은 방법으로는 변환할 수 없다. 따라서 Convert 클래스를 이용하여 변환한다.

  • ToInt16 : 16비트 정수로 변환
  • ToInt32 : 32비트 정수로 변환
  • ToUInt16 : 부호 없는 16비트 정수로 변환
  • ToUInt32 : 부호 없는 32비트 정수로 변환
  • ToDouble : double 타입으로 변환
  • ToString : 문자열로 변환
  • ToBoolean : 논리형으로 변환

 

2) while 문

while(조건식)
	구문;
    
// 또는

while(조건식) 구문;

조건식을 평가하고 참이면 구문을 실행한다. 조건식이 거짓이 될 때까지 무한 반복된다.

 

ex)

int i_count;
i_count = 5;

while(i_count > 0)
{
	Console.WriteLine("i_count : {0}", i_count);
	i_count--;
}

 

예제 실행 화면

 

int n = 1, sum = 0;

while(n < 1000)
{
	if( n % 3 == 0 || n % 5 == 0 )
	{
		sum = sum + n;
	}
	n++;
}
Console.WriteLine(sum);

 

예제 실행 화면

 

3) for 문

for( 초기화 ; 조건식 ; 반복문 )
	구문;
  
// 또는

for( 초기화 ; 조건식 ; 반복문) 구문;

최초 for문 구문에 진입할 때 초기화 코드가 실행되고, 이후 조건식 → 구문 → 반복문을 번갈아 가며 조건식의 평가 결과가 bool 타입으로 false가 될 때까지 실행을 반복한다.

 

ex)

int i_count;

for(i_count = 5 ; i_count > 0 ; i_count--)
{
	Console.WriteLine("i_count : {0}", i_count);
}

Console.WriteLine("i_count : {0}", i_count);

 

예제 실행 화면

 

int i_dan;
Console.Write("단수를 입력하세요(1~9) : ");
i_dan = int.Parse(Console.ReadLine());
int i_count;
for (i_count = 1 ; i_count < 10 ; i_count++)
{
	Console.WriteLine("{0} * {1} = {2}",i_dan ,i_count, i_count * i_dan);
}

 

예제 실행 화면

제어문은 기본적으로 구문 하나를 제어할 수 있지만 블록을 사용하는 경우 여러 개의 구문을 제어할 수 있다. 그리고 그 구문에는 다시 제어문이 포함될 수 있는데, for 루프 안에 또다시 for 루프가 있다면 이를 중첩 루프(nested loop)라고 한다.

 

ex)

int i_dan, i_count;

for(i_dan = 2; i_dan < 10 ; i_dan++)
{
	for (i_count = 1; i_count < 10; i_count++)
	{
		Console.WriteLine("{0} * {1} = {2}", i_dan, i_count, i_count * i_dan);
	}
	Console.WriteLine();
}

 

예제 실행 화면

 

4) do while 문

do
	구문;
while(조건식);

	//또는

do 구문 while(조건식);

먼저 구문을 실행하고 조건식을 평가한다. 실행 순서는 구문 → 조건식 → 구문 →조건식 ··· 으로 조건식이 거짓이 될 때까지 무한 반복된다. while 문과는 다르게 do/while 문은 반복 실행돼야 할 구문이 최소 한 번은 실행된다.

 

5) break 문

break문은 반복문 내에서만 사용할 수 있다. switch에서 사용하는 경우 해당 case 실행을 벗어나는 역할을 하고, 반복문 내에서 사용하는 경우 break를 둘러싸고 있는 첫 번째 반복문을 탈출한다.

 

ex)

int i = 2;
while(true)
{
	int j = 1;
	while(true)
	{
		Console.WriteLine(i + "*" + j + "=" + (i * j));

		if(++j >9)
		{
			break;
		}
	}
	Console.WriteLine();
	if(++i>9)
	{
		break;
	}
}

 

예제 실행 화면

 

6) continue 문

continue문은 이후의 반복 구문 실행을 생략하고 곧바로 조건식 평가로 실행을 옮기면서 반복을 계속한다.

 

ex) 짝수의 합을 구하는 소스

int sum = 0;
int n = 1;

while(n++<=1000)
{
	if((n % 2)!= 0)
	{
		continue;
	}
	sum += n;
}

Console.WriteLine("sum : {0}",sum);

 

예제 실행 화면

ex)

int iCommand;
while(true)
{
	Console.WriteLine("====================");
	Console.WriteLine("======= 메뉴 =======");
	Console.WriteLine("= 1. 안녕          =");
	Console.WriteLine("= 2. 헬로          =");
	Console.WriteLine("= 3. 종료          =");
	Console.WriteLine("====================");
	iCommand = int.Parse(Console.ReadLine());
	if((iCommand < 1) || (iCommand > 3))
	{
		continue;
	}
	if(iCommand == 1)
	{
		Console.WriteLine("안녕");
	}
	else if (iCommand == 2)
	{
		Console.WriteLine("헬로");
	}
	break;
}

 

예제 실행 화면

 

7) goto 문

제어문의 원조격인 문법이지만 다른 구조적인 구문이 나오면서 잘 사용하지 않는다. goto문은 코드의 가독성이 현저히 떨어져 코드 구조를 파악하기 쉽지 않기 때문이다.

 

cf. 순서도(FlowChart)

약속된 기호를 사용하여 해결하고자 하는 문제의 논리적 흐름을 약속된 도형으로 나타낸 것

프로그램 코딩의 기초가 되며, 프로그램의 오류 수정을 용이하게 한다. 또한 전체적인 논리의 흐름을 파악하는 것이 용이해지므로 업무의 인수인계나 프로그램의 유지 보수의 기본자료로 이용될 수 있다.

 

순서도 기호

 

8) 메서드(method)

이어지는 코드들을 묶어놓은 코드 블록으로 C언어에서는 함수(function), 서브루틴(subroutine), 프로시저(procedure)라고도 한다.  메서드명은 변수 명명 규칙에 따라 사용자가 임의의 이름을 지정할 수 있다.

//메서드가 값을 반환하는 경우
반환타입 메서드명([타입명] [매개변수명], ...)
{
	//코드 : 메서드의 본문(body)
    return [반환타입에 해당하는 표현식];
}

//메서드가 값을 반환하지 않는 경우
void 메서드명([타입명] [매개변수명], ...)
{
	//코드:메서드의 본문(body)
}

클래스를 기반으로 하는 C# 언어에서는 클래스 밖에서 메서드를 정의할 수 없다. 값을 반환하지 않는 메서드는 특별히 반환 타입으로 void라는 예약어를 명시하고, 메서드의 본문에는 return 문이 없어도 된다. 메서드는 외부에서 값을 전달받을 수 있으며, 이 값을 코드에서 식별하기 위해 인자(Arguments), 매개변수(parameter)를 함께 명시할 수 있다. 매개변수명은 메서드의 본문 내에서 일반적인 변수처럼 사용할 수 있다. 전달할 값이 없다면 생략할 수 있다.

 

ex)

static void Main(string[] args)
{
	test_1(); // 메서드 test_1 호출
	test_2(); // 메서드 test_2 호출
	test_3(100);
	test_3(50);
	test_4(100, 50);
	test_5();
	int i_num = test_5();
	Console.WriteLine("Main : {0}",i_num);
}
        
static void test_1()
{
	Console.WriteLine("test_1");
}

static void test_2()
{
	Console.WriteLine("test_2");
}
       
static void test_3(int i_test3)
{
	Console.WriteLine("test_3 : [" + i_test3 + "]");
}

static void test_4(int i_test41, int i_test42)
{
	Console.WriteLine("test_4 : [" + i_test41 + "," + i_test42 + "]");
}

static int test_5()
{
	Console.WriteLine("test_5");
	return 21;
}

 

예제 실행 화면

 

static void Main(string[] args)
{
	int number_1 = 200, number_2 = 10;
	Console.WriteLine("{0} + {1} = {2}", number_1, number_2, add(number_1, number_2));
	Console.WriteLine("{0} - {1} = {2}", number_1, number_2, sub(number_1, number_2));
	Console.WriteLine("{0} * {1} = {2}", number_1, number_2, mul(number_1, number_2));
	Console.WriteLine("{0} / {1} = {2}", number_1, number_2, div(number_1, number_2));
}

static int add(int i_num1, int i_num2)
{
	return i_num1 + i_num2;
}

static int sub(int i_num1, int i_num2)
{
	return i_num1 - i_num2;
}

static int mul(int i_num1, int i_num2)
{
	return i_num1 * i_num2;
}

static int div(int i_num1, int i_num2)
{
	return i_num1 / i_num2;
}

 

예제 실행 화면

 

static void Main(string[] args)
{
	while(true)
	{
		menu();
		int i_num = int.Parse(Console.ReadLine());
		if (i_num >= 1 && i_num <= 4)
		{
			int i_num1 = int.Parse(Console.ReadLine());
			int i_num2 = int.Parse(Console.ReadLine());
			if (i_num == 1)
			{
				Console.WriteLine("{0} + {1} = {2}", i_num1, i_num2, add(i_num1, i_num2));
			}
			else if (i_num == 2)
			{
				Console.WriteLine("{0} - {1} = {2}", i_num1, i_num2, sub(i_num1, i_num2));
			}
			else if (i_num == 3)
			{
				Console.WriteLine("{0} * {1} = {2}", i_num1, i_num2, mul(i_num1, i_num2));
			}
			else
			{
				Console.WriteLine("{0} / {1} = {2}", i_num1, i_num2, div(i_num1, i_num2));
			}
		}
		else if (i_num == 5)
		{
			break;
		}
		else
		{
			Console.WriteLine("값을 잘못입력하셨습니다.");
		}
	}        
}

static void menu()
{
	Console.WriteLine("====================");
	Console.WriteLine("==계산기 프로그램 ==");
	Console.WriteLine("= 1. 덧셈          =");
	Console.WriteLine("= 2. 뺄셈          =");
	Console.WriteLine("= 3. 곱셈          =");
	Console.WriteLine("= 4. 나눗셈        =");
	Console.WriteLine("= 5. 종료          =");
	Console.WriteLine("====================");
}
        
static int add(int i_num1, int i_num2)
{
	return i_num1 + i_num2;
}

static int sub(int i_num1, int i_num2)
{
	return i_num1 - i_num2;
}

static int mul(int i_num1, int i_num2)
{
	return i_num1 * i_num2;
}

static int div(int i_num1, int i_num2)
{
	return i_num1 / i_num2;
}

 

예제 실행 화면

cf. Main메서드

Main 메서드는 프로그램의 시작점, 진입점(Entry point)을 담당하는 특별한 식별자이다.

  • 메서드 이름은 반드시 Main
  • 정적 메서드(static)
  • Main 메서드가 정의된 클래스의 이름은 제한이 없다. 하지만 2개 이상의 클래스에서 Main 메서드를 정의하고 있다면 C# 컴파일러에게 클래스를 지정해야 한다.
  • Main 메서드의 반환값은 void 또는 int만 허용된다.
  • Main 메서더의 매개변수는 없거나 string 배열만 허용된다.

 

 

test)

1. 2부터 100까지 정수에서 소수를 구하는 프로그램을 작성하여 결과와 소스를 캡처하여 파일로 제출하시오
2. 실행시 첫 4줄은 그림을 참고하여 작성하시오
3. 중복 반복문을 이용하여 작성하시오
4. 캡쳐 그림은 개인 텔레그램을 통해 파일로 제출하시오(사진으로 보내기를 선택하면 안 됨)

 

실행 화면

Console.WriteLine("과정명 : 스마트팩토리 과정");
Console.WriteLine("교과목 : C# 기초");
Console.WriteLine("응시일 : 2020.05.26.");
Console.WriteLine("응시자 : 김한진");
            
int i_num;
for(int i = 2;i < 101 ; i++)
{
	i_num = 0;
	for(int j = 2 ; j <= i ; j++)
	{
		if(i % j == 0)
		{
			i_num = j;
			break;
		}
	}
	if(i_num == i)
	{
		Console.Write("{0} ", i);
	}
}
Console.WriteLine();

 

실행 화면

COMMENT