C로 “hello, world”를 출력하는 프로그램을 만들 수 있습니다.
#include <stdio.h>
int main(void)
{
printf("hello, world");
}
hello.c
파일을 생성하고 위의 코드를 작성합니다. (cf. .c
: c 언어 파일 확장자)prinf
: print formatted$ clang hello.c
$
: "Write something here". (Prompt, Shell)clang
: 코드를 컴파일하는 프로그램의 이름$ ./a.out
printf("hello, world\n");
\n
을 추가해 주었습니다.C로 문자열 형식을 가진 변수를 선언하고 출력하는 프로그램을 만들 수 있습니다.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
string answer = get_string("What's your name?\n");
printf("hello, %s\n", answer);
}
string answer = get_string("What's your name?\n");
string answer
: C에서는 변수를 선언 시 어떤 데이터 타입인지 정확하게 명시해줘야 합니다.string
을 형식지정자라고 부릅니다. get_string
함수가 사용자의 이름을 반환하면 그 이름을 anwser
라는 변수에 저장합니다.=
)를 사용합니다.#include <cs50.h>
$ clang -o string string.c -lcs50
(-lcs50
: link cs50)make
명령어를 통해 간단하게 컴파일을 수행할 수도 있습니다.$ make string
string.c
파일을 찾아 자동으로 컴파일 과정을 거친 string
파일을 생성해줍니다.조건문과 루프를 c로 작성할 수 있습니다.
init counter = 0;
counter = counter + 1;
counter += 1;
counter++;
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")
}
x == y
: 일치 연산자(==
)를 사용하여 두 개의 값이 같다는 것을 표현합니다.if(x < y)
{
printf("x is less than y.\n")
}
else if(x > y)
{
printf("x is greater than y.\n")
}
else
{
printf("x is equal to y.\n")
}
while (true)
{
printf("hello, wolrd.\n");
}
int i = 0;
while (i < 50)
{
printf("hello, wolrd.\n");
i = i + 1;
}
i
: integerfor(int i = 0; i < 50; i++)
{
printf("hello, wolrd.\n");
}
for(변수 초기화; 변수 조건; 변수 증가)
- 다양한 데이터 타입과 형식 지정자를 나타내는 방법을 학습합니다.
- 다양한 연산자를 이용하여 조건문을 표현하는 방법을 학습합니다.
printf 함수에서는 각 데이터 타입을 위한 형식 지정자를 사용할 수 있습니다. 여러가지 데이터 타입 마다 사용되는 형식 지정자를 알아보도록 하겠습니다. (ex. printf("hello, %s\n", answer);
)
+
: 더하기, -
: 빼기, *
: 곱하기, /
: 나누기, %
: 나머지&&
: 그리고, ||
: 또는//
: 주석#include <cs50.h>
#include <stdio.h>
int main(void)
{
int age = get_int("What's your age?\n");
printf("You are at least %i days old.\n", age * 365);
}
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float price = get_float("What's the price?\n");
printf("Your totoal is %.2f.\n", price * 1.0625);
}
사용자 정의 함수와 중첩 루프를 작성할 수 있습니다.
Q. 사용자 정의 함수를 사용하는 것의 장점은 무엇일까요?
// Example #1
#include <stdio.h>
void cough(int n); // first line of function code
int main(void)
{
cough(3);
}
void cough(int n)
{
for (int i = 0; i < n; i++)
{
printf("cough\n");
}
}
// Example #2
#include <cs50.h>
#include <stdio.h>
int get_positive_int(void);
int main(void)
{
get_positive_int();
}
// 함수 왼쪽에 있는 단어는 출력을 의미하고(int)(type of its output)
// 괄호 안에 있는 단어는 입력을 의미(void > 인자가 필요 없는 경우)(type of its input)
// 입출력이 모두 없다면 void를 적어주면 됨
int get_positive_int(void)
{
int n; // garbage value
do
{
n = get_int("Positive Ingteger: ");
}
while(n < 1);
return n;
}
#include <cs50.h>
#include <stdio.h>
int main(void)
{
int n;
do
{
n = get_int("Size: ");
}
while (n < 1);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("#");
}
printf("\n");
}
}
메모리 용량이 프로그램의 구동에 미치는 영향을 설명할 수 있습니다.
#include <cs50.h>
#include <stdio.h>
int main(void)
{
float x = get_float("x: ");
float y = get_float("y: ");
printf("x / y = %.50f\n", x / y);
}
#include <stdio.h>
#include <unistd.h>
int main(void)
{
for (int i = 1; ; i *= 2) // 두 번째 input을 빈 칸으로 두었음. infinite loop
{
printf("%i\n", i);
sleep(1);
}
}
1999년에 큰 이슈가 되었던 Y2K 문제는 연도를 마지막 두 자리수로 저장했던 관습 때문에 새해가 오면 ‘99’에서 ‘00’으로 정수 오버플로우가 발생하고, 새해가 2000년이 아닌 1900년으로 인식된다는 문제였습니다. 그리고 세계는 수백만 달러를 투자해서 프로그래머들에게 더 많은 메모리를 활용해서 이를 해결하도록 하였습니다. 이는 통찰력 부족으로 발생한 아주 현실적이고 값비싼 문제였습니다.
또한 다른 사례로 비행기 보잉 787에서 구동 후 248일이 지나면 모든 전력을 잃는 문제가 있었습니다. 왜냐하면 강제로 안전 모드로 진입하였기 때문입니다. 이는 소프트웨어의 변수가 248일이 지난 뒤에 오버플로우가되어 발생하였기 때문이었습니다. 248일을 1/100초로 계산하면 대략 2의 32제곱이 나옵니다. 보잉을 설계할때 사용한 변수보다 너무 커졌던 것입니다. 이를 해결하기 위해 주기적으로 재가동을 하여 변수를 다시 0으로 리셋했습니다. 따라서 다루고자 하는 데이터 값의 범위를 유의하며 프로그램을 작성하는 것이 중요합니다.