[C] 8. 분기문

Taeil Nam·2022년 6월 13일
0

C

목록 보기
8/18
post-thumbnail

1. if

  • if의 조건식이 true일 경우 코드를 실행.
#include <stdio.h>

int main()
{
    int num = 0;	// 정수형 변수 num 초기화.

    printf("Enter the integer : ");
    scanf("%d", &num);	// 정수 입력 받고 변수 num에 저장.

    if (num % 2 == 0)	// num을 2로 나눈 나머지가 0일 경우. (조건식 = num % 2 == 0)
    {
        printf("Even\n");	// Even 출력.
    }

    return 0;
}

2. else

  • if의 조건식이 false 일 경우 코드를 실행.
#include <stdio.h>

int main()
{
    int num = 0;

    printf("Enter the integer : ");
    scanf("%d", &num);

    if (num % 2 == 0)	// num을 2로 나눈 나머지가 0일 경우.
    {
        printf("Even");	// Even 출력.
    }
    else	// num을 2로 나눈 나머지가 0이 아닐 경우.
    {
        printf("Odd");	// Odd 출력.
    }

    return 0;
}

3. else if

  • if문에서 또 다른 조건을 만들 때 사용.
#include <stdio.h>

int main()
{
    int num = 0;

    printf("Enter the integer : ");
    scanf("%d", &num);

    if (num % 2 == 0)	// num을 2로 나눈 나머지가 0일 경우.
    {
        printf("Even");	// Even 출력.
    }
    else if (num % 2 == 1)	// num을 2로 나눈 나머지가 1일 경우. (또 다른 조건)
    {
        printf("Odd");	// Odd 출력.
    }

    return 0;
}

4. switch case

  • 각 case에 맞는 코드를 실행.
#include <stdio.h>

int main()
{
    char c;

    printf("Enter the number - 1 or 2 or 3 : ");

    while ((c = getchar()) != '.')  // 변수 c에 저장된 문자가 '.' 이 아닌 경우 아래 코드 실행.
    {                               // getchar() = 문자를 입력받는 표준 입출력 함수.
        printf("You entered ");

        switch (c)  // c의 값에 맞는 case의 코드 실행.
        {
        case '1':   // c의 값이 '1'일 경우.
            printf("One");
            break;  // break가 없으면 밑의 코드까지 전부 실행됨.
        case '2':   // c의 값이 '2'일 경우.
            printf("Two");
            break;
        case '3':   // c의 값이 '3'일 경우.
            printf("Three");
            break;
        default:    // 모든 case에 해당하지 않는 경우.
            printf("Nothing");
        }
        printf(".\n");

        while (getchar() != '\n')   // 첫글자 뒤에 있는 글자들 무시.
            continue;   // 줄바꿈(\n)이 나올때까지 실행.
    }
    printf("End."); // '.' 을 입력받으면 while 종료 후 End 출력.

    return 0;
}
💡 반복문에서 continue, break

continue
- 반복문 수행 중 continue가 수행되면, 그 뒤의 코드를 스킵하고 반복문을 다시 수행.
break
- 반복문 수행 중 break가 수행되면, break가 속해있는 반복문 빠져나옴.

5. 논리 연산자(Logical Operator)

&&

  • and 조건

||

  • or 조건

!

  • not 조건

#include <stdio.h>

int main()
{
    int a, b;
    
    a = 1;
    b = 1;

    if (a == 1 && b == 1)	// a와 b 둘다 1인 경우.
    {
        printf("a and b = 1.\n");
    }
    else if (a == 1 || b == 1)	// a 또는 b가 1인 경우.
    {
        printf("a or b = 1.\n");
    }
    else if (a != b)	// a와 b가 다른 경우.
    {
        printf("a is not b.\n");
    }

    return 0;
}

iso646.h

  • 논리연산자를 and, or, not 으로 바꿔서 사용할 수 있께 해주는 라이브러리.
#include <stdio.h>
#include <iso646.h>	// 전처리기에서 iso646.h 라이브러리 호출.

int main()
{
    int a, b;

    a = 2;
    b = 3;

    if (a == 1 and b == 1)	// a와 b 둘다 1인 경우.
    {
        printf("a and b = 1.\n");
    }
    else if (a == 1 or b == 1)	// a 또는 b가 1인 경우.
    {
        printf("a or b = 1.\n");
    }
    else if (not(a == b))	// a와 b가 다른 경우.
    {
        printf("a is not b.\n");
    }

    return 0;
}

Short-Circuit Evaluation

  • 논리식의 연산은 왼쪽부터 수행.
  • and 논리 연산에서 왼쪽 논리식의 결과가 false인 경우, 오른쪽 논리식은 연산할 필요 없이 무시.
  • 이를 short-circuit evaluation 이라고 하며, 유용하게 사용 됨.
#include <stdio.h>

int main()
{
    int a, b;

    a = 2;
    b = 2;

    if (a == 1 && b == 1)	// a == 1 이 true이면 b == 1 확인. (short-circuit evaluation)
    {
        printf("a and b = 1.\n");
    }

    return 0;
}

6. 조건 연산자(Conditional Operator)

  • 삼항 연산자라고도 부름.
  • '?' 기호와 ':' 기호 사용.
  • '?' 앞의 조건식이 true일 경우, ':' 의 왼쪽 값 대입.
  • '?' 앞의 조건식이 false일 경우, ':' 의 오른쪽 값 대입.
  • 조건식은 가시성을 위해 소괄호(())로 묶어줌.
    Ex) is_even = (number % 2 == 0) ? true : false;
    조건식 number % 2 == 0 이 true이면, is_even 변수에 true 저장.
    조건식 number % 2 == 0 이 false이면, is_even 변수에 false 저장.
#include <stdio.h>
#include <stdbool.h>

int main()
{
	int number;		// 정수형 변수 number 선언.
	bool is_even;	// boolean형 변수 is_even 선언.

	printf("Enter a integer : ");
	scanf("%d", &number);	// 정수를 입력받아서 변수 number에 저장.
	is_even = (number % 2 == 0) ? true : false;	// 조건에 맞는 값을 변수 is_even에 저장.

	if (is_even)	// is_even의 값이 true일 경우.
		printf("Even");

	else			// is_even의 값이 false인 경우.
		printf("Odd");

	return 0;
}

🚩 출처 및 참고자료 : 홍정모의 따라하며 배우는 C 언어 (따배씨)

0개의 댓글