-
Conditionals, Boolean expressions | CS50 Week 1Computer Science/CS 50 Harvard 2021. 11. 6. 21:57
Condition
어떤 값을 비교하거나 상황에 맞게 Condition을 만들기 위해, if를 사용할 수 있다. 예를들면 아래와 같다.
if (x < y) { printf("x is less than y"); }
main method와 마찬가지로, { 와 } 를 이용해서, 어디까지 이 컨디션일때 해당하는지 표시해줄 수 있다. 또 if 는 (), 즉 parentheses와 함께 쓰여지는데 그 안에 조건을 넣어줄 수 있다. 그렇다면, 반대의 경우는 어떨까?
if (x < y) { printf("x is less than y\n"); } else { printf("x is not less than y\n"); }
x가 y와 같거나 y보다 클 경우, else를 사용해서 그 이외의 경우에는 다른 문장을 쓸 수 있다. 만약 이 이외에 더 다양한 조건문을 만들기 위해서는? else if를 사용할 수 있다.
if (x < y) { printf("x is less than y\n"); } else if (x > y) { printf("x is greater than y\n"); } else if (x == y) { printf("x is equal to y\n"); }
작을 경우, 클경우, 그리고 같을경우를 모두 나열해주었다. 마지막 else if 는 따로 조건을 주지 않고 else를 써도 무방하다.
Conditional Statements에 대해서는 추가 영상에서 더 자세하게 다루었다.
points
나의 점수와 상대방의 점수를 비교하는 프로그램을, Condition을 이용해서 만들어보자.
#include <cs50.h> #include <stdio.h> int main(void) { int points = get_int("How many points did you lose? "); if (points < 2) { printf("You lost fewer points than me.\n"); } else if (points > 2) { printf("You lost more points than me.\n"); } else if (points == 2) { printf("You lost the same number of points as me.\n"); } }
2점을 기준으로, 상대방의 input을 포인트로 받아서, 비교를 하고, 나와의 차이를 말해주는 프로그램이다. 컴파일을 하고 실행해보자.
> make points clang points.c -lcs50 -o points > ./points How many points did you lose? 1 You lost fewer points than me. > ./points How many points did you lose? 2 You lost the same number of points as me. > ./points How many points did you lose? 3 You lost more points than me.
만약 나의 점수가 3으로 바뀐다면? 코드에 3군데를 바꾸어주어야 한다. 이것을 방지하기 위해서 아래와 같이 코딩해볼 수 있다.
#include <cs50.h> #include <stdio.h> int main(void) { const int MINE = 3; int points = get_int("How many points did you lose? "); if (points < MINE) { printf("You lost fewer points than me.\n"); } else if (points > MINE) { printf("You lost more points than me.\n"); } else if (points == MINE) { printf("You lost the same number of points as me.\n"); } }
컴파일을 하면, 4이상이 되어야, 나보다 많이맞았네! 문장이 프린트된다. 그리고 이후, 내 점수가 바뀌어도 한군데만 바꾸어주면 된다.
> make points clang points.c -lcs50 -o points > ./points How many points did you lose? 1 You lost fewer points than me. > ./points How many points did you lose? 2 You lost fewer points than me. > ./points How many points did you lose? 3 You lost the same number of points as me. > ./points How many points did you lose? 4 You lost more points than me.
여기서, const라는 키워드는 컴파일러에게 중간이 이 값이 바뀌지 않게끔 알려주는 역활을 하고, 이 const variable은 모두 대문자로 쓴다.
const int MINE = 3;
parity
parity.c 라는 프로그램을 만들어보자.
> code parity.c
integer를 받아서, 짝수인지 홀수인지 말해주는 프로그램이다.
#include <cs50.h> #include <stdio.h> int main(void) { int n = get_int("n: "); if (n % 2 == 0) { printf("even\n"); } else { printf("odd\n"); } }
% 오퍼레이터는 n을 2로 나눈 후 나머지 값을 리턴한다. 만약 그 값이 0이면 짝수이고, 1이면 홀수이다.
아래와 같이 컴파일한 후, 테스트 할 수 있다.
> make parity clang parity.c -lcs50 -o parity > ./parity n: 2 even > ./parity n: 3 odd > ./parity n: 4 even > ./parity n: 0 even
재미있는 결과는 사람들이 조금 헷갈릴 수 있는 0이 even, 즉 짝수로 나온다 (0이 짝수라는 위키피디아).
agree
이번에는 유저의 동의를 받아 동의를 했는지 안했는지 출력하는 프로그램을 만들어보자.
#include <cs50.h> #include <stdio.h> int main(void) { // Prompt user to agree char c = get_char("Do you agree (Y/N)? "); // Check whether agreed if (c == 'Y' || c == 'y') { printf("Agreed.\n"); } else if (c == 'N' || c == 'n') { printf("Not agreed.\n"); } }
char를 받아서, Y 또는 N 일경우 해당하는 콘디션에 들어가서, 해당하는 문장을 출력하는 프로그램이다. 하지만 이 프로그램을 y 또는 n이 아닐 경우, 다시 물어본다던지 하는 동작은 개발이 안되어있기 때문에 추후 발전할만한 사항이 보이는 코드이다.
get_char는 유저에게 char를 받아서 저장할 수 있게끔 해준다. if에서 사용된 || 는, or, 즉 또한 이라는 의미이다. 혹시 유저가 대문자 또는 소문자로 입력했을 가능성을 모두 포함시킨것이다. 만약 and 라는 표현을 하려면 && 을 사용할 수 있다.
char를 표현할때는 single qutoe(') 를 사용하고 string을 표현할때는 double quote(")를 사용한다. 만약 스트링에 한 캐릭터가 있는데 ""를 사용했다면, char가 아닌 string이다.
"a" //string 'a' // char
Reference
'Computer Science > CS 50 Harvard' 카테고리의 다른 글
Mario | CS50 Week 1 (0) 2021.11.07 Loops, functions | CS50 Week 1 (0) 2021.11.06 Calculations | CS50 Week 1 (0) 2021.11.06 Variables, syntactic sugar | CS50 Week 1 (0) 2021.11.06 Types, format codes, operators | CS 50 Week 1 (0) 2021.11.06