줘이리의 인생적기

C - 조건문(if, switch ~ case) 본문

공부/C

C - 조건문(if, switch ~ case)

줘이리 2020. 5. 12. 13:46
728x90

 

Index

  • if
  • if ~ else
  • if ~ else if ~ else
  • if 중첩
  • switch ~ case

1. if

기본 구조를 알아보고 예제로 이해하기

if문 기본 구조

if문 예제

#include <stdio.h>

int main(void)
{
	int a = 15;
	int b = 1;

	if (a > 10)          
	{
		b = a;   
	}

	printf("a : %d, b : %d\n", a, b);  

	return 0;
}

 

실행결과

 

 

2. if ~ else

만족하지 못할 때에도 실행코드를 넣으려면 사용하는 조건문

 

if ~ else문 예제

#include <stdio.h>

int main(void)
{
	int a = 5;

	if (a >= 0)
	{
		a = 4;		
	}
	else
	{
		a = 3;		
	}

	printf("a : %d\n", a);

	return 0;
}

실행결과(충분한 생각을 가진 후 누르기)

 

 

3. if ~ else if ~ else

3개 이상의 실행문 중 하나를 선택하는 경우의 조건문

 

if ~ else if ~ else 예제

#include <stdio.h>

int main(void)
{
	int a = 0, b = 0;

	if (a > 0)              
		b = 5;
	
	else if (a == 0)        
		b = 3;
	
	else                    
		b = 1;
	

	printf("b %d\n", b);  

	return 0;
}

실행결과(충분한 생각을 가진 후 누르기)

 

 

 

4. if 중첩

어떤 조건을 검사하기 전에 선행조건이 있다면 사용하는 조건문

 

if 중첩 예제

#include <stdio.h>

int main(void)
{
	int a = 5, b = 0;

	if (a > 0)       
	{
		if (b >= 0)  
		{
			b = 1;
		}
		else
		{
			b = -1;  
		}
	}

	printf("a는%d, b는%d\n", a, b);

	return 0;
}

실행결과(충분한 생각을 가진 후 누르기)

 

※여기서 주의 해야 할 점 : dangling else problem(매달린 else 문제)

https://yiunsr.tistory.com/122

 

[버그킬러] Dangling else problem(else는 누구것??)

오늘 저를 괴롭했던, 문제의 샘플입니다. ======================================================================= #include int main() { if(1 == 0 ) if( 1 == 1) printf("1번"); else printf("2번..

yiunsr.tistory.com

이 분의 사이트를 참고하세요!

 

 

5. switch ~ case

여러 개의 상수 중에서 조건에 해당하는 하나를 골라 실행하는 조건문

(조건식은 정수만 사용, default의 위치는 어디 있어도 무관)

 

switch ~ case 예제

#include <stdio.h>

int main(void)
{
	int rank = 2, money = 0;

	switch (rank)	
	{
	case 1:			
		money = 3000;	
		break;		
	case 2:			
		money = 2000;	
		break;		
	case 3:			
		money = 1000;	
		break;		
	default:		
		money = 500;		
		break;		
	}

	printf("받는 돈은 %d원\n", money);

	return 0;
}

실행결과(충분한 생각을 가진 후 누르기)

 

 

지적 및 개선사항은 언제든지 댓글로 부탁드립니다!

'공부 > C' 카테고리의 다른 글

C - 함수  (0) 2020.05.12
C - 반복문(while, for, do ~ while)  (0) 2020.05.12
C - 연산자  (0) 2020.05.12
C - 변수와 데이터 입력  (0) 2020.05.12
C - 상수와 데이터 출력  (0) 2020.05.11