CS

[모두의 컴퓨터과학] C언어 기초

KSWKSW 2021. 11. 14. 00:34

C 기초

  • 오래되고 전통적인 순수 텍스트 기반의 언어
#include <stdio.h>

int main(void)
{
    printf("hello, world");
}
  • int main(void)는 스크래치에서 시작하는 블록과 비슷하다. 모든 코드는 중괄호 안에 들어간다.
  • printf: 형식화(formating) 된 print, 문자는 쌍따옴표로 감싸야함
  • 코드 각줄 마지막에 세미콜론을 붙임
  • #include <stdio.h>: 컴퓨터에게 함수가 어디에 저장되어 있는지 알려주는 말
  • C언어는 코드를 저장할때 .c 확장자를 사용한다.
  • 코드를 컴퓨터가 이해할 수 있도록 0과 1로 번역하는 과정을 수행하는 소프트웨어를 compiler라고 한다.
  • clang: 코드를 컴파일하는 프로그램 이름
  • clang hello.c를 프롬프트에 입력해서 a.out 파일을 만든다.
  • 새로운 줄로 바꾸고 싶다면 \n을 이용한다.

문자열

  • get_string: 문자열 입력을 받아 변수에 저장
  • C는 변수가 저장하는 데이터 종류를 명시해줘야 함.
  • %s: 문자열을 의미하는 형식 지정자
  • 문자열과 get_string 함수를 저장하고 있는 저장하고 있는 라이브러리를 연결하는 명령어가 필요하다.(-l)
  • 코드를 컴파일할 때 make 명령어를 사용하면 자동으로 만들어준다.

조건문과 루프

  • int counter = 0; 으로 변수를 할당한다.
  • counter = counter + 1 로 카운트를 증가시킨다. int를 쓸 필요는 없다.
  • counter += 1;, counter++; 이라고 쓸 수도 있다.

조건

  • if과 else
if (x < y)
{
    printf("x is less than y\n");
}
else
{
    printf("x is not less than y]n");
}
  • 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)
{
    print("x is equal to y\n");
}
  • if ... else if ... else 형태로 사용할 수도 있다.

루프

  • while (true) = forever
while (true)
{
    printf("hello, world");
}
  • 50회만 반복
int i = 0;
while (i < 50)
{
    printf('hello, world\n');
    i += 1;
}
  • for 루프
for (int i = 0; i < 50; i++)
{
    printf("hello, world\n");
}

자료형

  • bool: 참/거짓
  • char: 한 개의 문자
  • int: 정수
  • string: 문자열
  • long: int는 40억까지 셀 수 있지만 더 많은 비트를 사용해 큰 숫자를 센다
  • float: 소수
  • double: 소수점뒤에 더 많은 숫자를 가질 수 있음
  • 각 자료형마다 get_ 함수가 있음

형식 지정자

  • %c: char
  • %f: float, double
  • %i: int
  • %li: long
  • %s: string

예제 1

#include <cs50.h>
#include <stdio.h>

int main(void)
{
    int age = get_int("What's your age?\n");
    int days = age * 365;
    printf("You ar at least %i days old.\n", days)
}

예제 2

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    float price = get_float("What's the price?\n");
    printf("Your total is %.2f\n", price * 1.0625);
}
  • %.2f: 소숫점 2번째 자리까지만 프린트

예제 3

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    int n = get_int("n:");
    if (n % 2 == 0)
    {
        printf("even\n");
    }
    else
    {
        printf("odd\n");
    }
}
  • //로 주석을 작성할 수 있다.
  • ||는 or를, &&는 and를 의미한다.
  • 실제 C언어에서는 <cs50.h>의 get_ 함수가 아니라 scanf()로 입력을 받는다.

사용자 정의 함수

#include <stdio.h>

// 괄호안에 void: 입력을 받지 않음
// 앞쪽의 void: 값을 반환하지 않음

void cough(void);

int main(void)
{
    for (int i = 0; i < 3; i++)
    {
        cough();
    }
}

void cough(void)
{
    printf("cough\n");
}
  • main을 위로 올리고 싶으면 코드 윗부분에 void cough(void); 로 선언해준다.
  • 횟수를 입력받아 cough를 실행함
#include <stdio.h>

void cough(int n);

int main(void)
{
    cough(3);
}

void cough(int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("cough\n");
    }
}
  • 양수를 반환하는 함수
#include <stdio.h>
#include <cs50.h>

int get_positive_int(void)
{
    int n;
    do
    {
        n = get_int("positive integer: ");
    }
    while (n < 1);
    return n;
}
  • do - while 문은 한번 코드를 실행하고 조건을 확인하는 while 루프다.
  • 루프는 중첩하여 사용할 수 있다.
#include <stdio.h>
#include <cs50.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");
    }
}

하드웨어의 한계

  • 모든 컴퓨터, 스마트폰 등은 RAM을 사용한다.
  • 컴퓨터가 여러 일들을 한번에 할 때 기억하기 위해 RAM을 사용한다.
  • 이 메모리의 용량은 유한하기 때문에 컴퓨터가 하는 연산은 한계가 있다.
  • 컴퓨터에게 1 / 10을 시켰을 때, 값이 0.1이 나오지 않고 다른 숫자가 나온다. => 메모리에 저장할 수 있는 값이 한계가 있기 때문
  • 정수가 너무 커지면 overflow가 일어나 0이 된다.

출처: 부스트코스 모두의 컴퓨터과학