C언어 기초(3) : if else, switch

STUDY_J·2024년 6월 28일

기초 문법

  • and : &&
  • or : ||

if else

  • 나이를 입력받아 20세 이상이면 Adult, 그렇지 않으면 Student로 출력하는 코드
#include <stdio.h>

int main(){

	//int age = 15;
	int age;
	printf("What's your age?");
	scanf("%d", &age);
	
	if(age>=20){
		printf("Adult\n");
	}
	else{
		printf("Student\n");
	}	
	return 0;

}

(주의점 : scanf에서는 줄 띄어쓰기인 "%d\n"를 사용하지 않는다. scanf에서는 "%d"만 사용.)

  • 조건을 많이 만들기 (초등학생, 중학생, 고등학생으로 나눠서 출력해보기)
#include <stdio.h>

	int age;
	printf("What's your age?");
	scanf("%d", &age);
	
	if(age >= 8 && age <= 13){
		printf("Elementry\n");
	}
	else if(age >=14 && age <= 16){
		printf("Middle\n");
	}
	else if(age >=17 && age <= 19){
		printf("High\n");
	}
	else{
		printf("Not in range\n");
	}
	return 0;
}

여기서는 해당 범위에 포함되지 않는 나이가 입력되면 not in range를 출력하도록 설정하였다.

  • 심화버전으로 3개의 입력을 받고, 나이를 판별하여 각각의 입력값에 대한 출력을 하는 방법
#include <stdio.h>

int main() {
    int age1, age2, age3;
    printf("Enter three ages : ");
    scanf("%d %d %d", &age1, &age2, &age3);
    
    // Check the first age
    if (age1 >= 8 && age1 <= 13) {
        printf("First age: Elementary\n");
    } else if (age1 >= 14 && age1 <= 16) {
        printf("First age: Middle\n");
    } else if (age1 >= 17 && age1 <= 19) {
        printf("First age: High\n");
    } else {
        printf("First age: Not in range\n");
    }
    
    // Check the second age
    if (age2 >= 8 && age2 <= 13) {
        printf("Second age: Elementary\n");
    } else if (age2 >= 14 && age2 <= 16) {
        printf("Second age: Middle\n");
    } else if (age2 >= 17 && age2 <= 19) {
        printf("Second age: High\n");
    } else {
        printf("Second age: Not in range\n");
    }
    
    // Check the third age
    if (age3 >= 8 && age3 <= 13) {
        printf("Third age: Elementary\n");
    } else if (age3 >= 14 && age3 <= 16) {
        printf("Third age: Middle\n");
    } else if (age3 >= 17 && age3 <= 19) {
        printf("Third age: High\n");
    } else {
        printf("Third age: Not in range\n");
    }
    
    return 0;
}


올바른 값들을 출력한다.
각 age마다 if else문을 작성해야하는 번거로움이 있는데, 이를 for문을 사용해서 코드를 단순하게 만들 수 있지 않을까..? (고민해보기)

break, continue

  • 1번부터 30번까지 학생중에서 1~5번 까지만 조별 발표를 할때
#include <stdio.h>

int main(){

	for(int i = 1; i <= 30; i++){
	
		//printf("Prepare your presentation No.%d student\n", i);
		if(i >= 6){
			printf("The rest of the students can go home\n");
			break;
		}
		printf("Prepare your presentation No.%d student\n", i);
	}

}

여기서 printf의 위치에 따라 "나머지 학생들은 집에 가도 좋다"는 출력값이 달라지므로 주의해야함

if문 위에 printf가 있다면 i=6 일 때도 출력이 되므로 if문을 탈출한 후에 printf가 출력되도록 한다.

  • 7번 학생이 결석한 상황에서 7번을 제외하고 6번부터 10번까지 조별 발표를 준비하라고 출력하고 싶다면?
#include <stdio.h>

int main(){
	for(int i = 1; i <= 30; i++){
	
		if(i>=6 && i<=10){
			if( i == 7){
				printf("No.%d student is absent\n", i);
				continue;
			}
			printf("Prepare your presentation No.%d student\n", i);
		}
	
	}

}

  • break의 쓰임 : 조건을 만족할 때 break 를 만나면 코드가 중단됨
  • continue의 쓰임 : continue를 만나면 다음 코드만 실행되지 않고 다시 반복문을 수행함

random

  • 랜덤을 사용하기 위해서는 헤더 파일을 작성할 때 주의해야함
    기존의 #include <stdio.h> 에 추가적으로 <time.h>를 작성해야한다.
    (파이썬에서 import 같은 느낌)
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(){
	//srand(time(NULL)); // Reset
	//int num = rand() % 3+1; // 퍼센트 뒤의 숫자는 범위를 의미한다. 여기서는 0~2를 나타내고, 3+1로 바꿔주면 1~3범위로 변경된다.
	
    
    printf("Before reset..\n");
	for(int i = 0; i <10; i++){
		printf("%d ", rand() % 10);
	}
	
	srand(time(NULL)); 난수를 초기화 해주기 위함.
	printf("\n\nAfter reset..\n");
	for(int i = 0; i <10; i++){
		printf("%d ", rand() % 10);
	}
	
	return 0;
}

switch case

  • 가위바위보 게임 만들기
#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(){

	//S = 0 R = 1  P = 2  game
	srand(time(NULL));
	int i = rand() % 3; //0~2
	if(i == 0){
		printf("scissor\n");
	}
	else if(i==1){
		printf("rock\n");
	}
	else if(i==2){
		printf("paper\n");
	}
	else{
		printf("Nothing\n");
	}
	
}

위 코드를 switch case 를 사용하여 작성할 수 있다.

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(){

	srand(time(NULL));
	int i = rand() % 3; //0~2
	switch(i){
	case 0:printf("scissor\n");
	case 1:printf("rock\n");
	case 2:printf("paper\n");
	default:printf("Nothing\n");
	}	
}

이대로 출력을 해보면 다음과 같이 가위바위보 중 하나를 출력하고, 나머지 값들도 출력하게 된다.
이는 switch case 구문에서, 해당 조건과 일치하면 그 다음 조건들은 확인도 하지 않고 출력이 된다.

다음 상황에서는 random 값으로 2가 들어와서 paper를 출력했지만 그 다음 값인 Nothing을 출력하고,
random 값으로 1이 들어오면 scissor를 출력하고 그 다음 모든 case들을 출력하는 결과를 보여준다.

이런 결과를 방지하기 위해서는 case뒤에 break를 사용하여 해당 조건을 출력했으면 탈출하도록 설정을 해야한다.

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

int main(){
	srand(time(NULL));
	int i = rand() % 3; //0~2
	switch(i){
	case 0:printf("scissor\n");break;
	case 1:printf("rock\n");break;
	case 2:printf("paper\n");break;
	default:printf("Nothing\n");break;
	}	
}

if else 구문을 사용한 코드를 switch case로 바꿔보기

#include <stdio.h>

int main(){

	int age;
	printf("What's your age?");
	scanf("%d", &age);
	
	switch(age){
	
		case 8:printf("Elementry\n");break;
		case 9:printf("Elementry\n");break;
		case 10:printf("Elementry\n");break;
		case 11:printf("Elementry\n");break;
		case 12:printf("Elementry\n");break;
		case 13:printf("Elementry\n");break;
		case 14:printf("Middle\n");break;
		case 15:printf("Middle\n");break;
		case 16:printf("Middle\n");break;
		case 17:printf("High\n");break;
		case 18:printf("High\n");break;
		case 19:printf("High\n");break;
		default:printf("Nothinh\n");break;
	}
	
	return 0;
}

위의 코드는 case 뒤에 출력되는 값이 너무 중복된다.

따라서 초등학생을 출력하기 위해서 8~12 뒤의 printf는 지워주고, 중학생을 출력하기 위해서는 14,15를, 고등학생을 출력하기 위해서는 17,18의 printf를 지워준다.

그렇게 되면 만약 11이 들어온다면 뒤의 출력값이 없으므로 진행되다가 13과 만나서 초등학생을 출력하고 탈출한다.

15가 들어온다면 진행되다가 case16에서 출력을 하고 break를 만나 탈출한다.

#include <stdio.h>

int main(){

	int age;
	printf("What's your age?");
	scanf("%d", &age);
	
	switch(age){
	
		case 8: 
		case 9:
		case 10:
		case 11:
		case 12:
		case 13:printf("Elementry\n");break;
		case 14:
		case 15:
		case 16:printf("Middle\n");break;
		case 17:
		case 18:
		case 19:printf("High\n");break;
		default:printf("Nothinh\n");break;
	}
	
	return 0;
}

프로젝트

  • Up and down
    (주의점 : rand 값의 범위를 설정할때, 100으로 한다면 0~99까지의 범위이므로, 100 + 1로 설정하여 1~100 의 범위가 되도록 설정한다.)
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(){
	
	srand(time(NULL));
	int num = rand() % 100 + 1;
	printf("%d\n", num);
	
	int a;
	while(num != a){
		printf("Put your number : ");
		scanf("%d", &a);
		
		if(num > a){
			printf("Up\n");
		}
		else if(num < a){
			printf("Down\n");
		}
		else if(num == a){
			printf("Congratulation!\n");
		}
	}
	
	return 0;
}
  • 심화버전 (10번의 기회안에 맞추는 게임)
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int main(){
	
	srand(time(NULL));
	int num = rand() % 100 + 1;
	//printf("%d\n", num);
	
	int a;
	for(int i=10;i>0;i--){
		printf("Put your number(1~100) : ");
		scanf("%d", &a);
	
		if(num > a){
			printf("----Up----");
		}	
		else if(num < a){
			printf("----Down----");
		}
		else if(num == a){
			printf("Congratulation!\n");
			break;
		}

		printf("\n남은 기회 %d 번\n", i-1);
	
	}

	return 0;
}

0개의 댓글