전공/C
과제 4 - Control Flow (1 ~ 5)
yha97
2021. 6. 21. 15:17
if~else문, 그리고 switch문을 통해 해결하는 문제가 주를 이루었다.
개인적으로 switch는.... 너무 귀찮았다.
if~else문을 통해 입력받은 수가 양수인지, 음수인지, 혹은 0인지를 판별, 결과를 출력하는 프로그램이다.
if, else if, else를 활용하여 간단하게 해결 가능하다.
#include <stdio.h>
int main(){
int n;
printf("Enter any number: ");
scanf("%d", &n); // inputs the number from user
// check whether the number is positive or not or zero then prints output
if(n > 0){
printf("Number is POSITIVE\n");
}
else if(n < 0){
printf("Number is NEGATIVE\n");
}
else{
printf("Number is ZERO");
}
return 0;
}
char 변수를 하나 입력받고 해당 알파벳이 자음(Consonant)인지, 모음(Vowel)인지를 판별, 결과를 출력하는 프로그램이다.
a, i, e, o, u 에 case를 붙여 Vowel을 출력하고, defalut문을 통해 Consonant를 출력하면 해결 가능하다.
이 또한 Q1처럼 if, else문을 통해 해결 가능하다.
#include <stdio.h>
int main(){
char c;
printf("Enter any character: ");
scanf("%c", &c); // inputs character from user
// check if character is upper of lower
if(c > 97)
c -= 32;
// check if character is vowel or consonant, then print result
if(c == 'A')
printf("Vowel");
else if(c == 'I')
printf("Vowel");
else if(c == 'E')
printf("Vowel");
else if(c == 'O')
printf("Vowel");
else if(c == 'U')
printf("Vowel");
else
printf("Consonant");
return 0;
}
소문자를 입력받은 경우 대문자만을 기준으로 값을 측정해야 하기 때문에 32를 빼주는 것을 주의해야 한다.
이 문제는 Q3를 switch문을 통해 해결하는 문제이다.
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
printf("Enter any number: ");
scanf("%d", &n); // inputs the number from user
int temp = 0;
// check if number is zero
switch(n){
case 0:
printf("Number is ZERO");
break;
default:
temp = n / abs(n);
}
// if the number is not zero, check if that is positive or negative
switch(temp){
case 1:
printf("Number is POSITIVE");
break;
case (-1):
printf("Number is NEGATIVE");
break;
}
return 0;
}
character를 입력받고 해당 문자가 스펠링인지, 숫자인지, 혹은 특수문자인지 판별하여 출력하는 프로그램이다.
#include <stdio.h>
int main(){
char c;
printf("Enter any character: "); // inputs character from user
scanf("%c", &c);
// check case with ASCII codes
if(c >= 65 && c < 91) // alphabet(larger)
printf("'%c' is alphabet.", c);
else if(c >= 97 && c < 123)
printf("'%c' is alphabet.", c); // alphaber(smaller)
else if(c >= 48 && c < 58) // digit number
printf("'%c' is digit.", c);
else // etc
printf("'%c' is special character.", c);
return 0;
}
아스키 코드표를 참고하여 문제를 해결하면 된다.
Q4를 switch문을 통해 구현하는 문제이다.
코드 길이가 길어 생략.... (일일히 다 case를 생성해서 문제를 해결했다. 특수문자는 default 처리함)