C/Fundamentals

C fundamentals (1)

metamong 2023. 6. 16.

✊ C언어의 기초 본격적인 시작!

1) fundamentals

//text-based language
#include <stdio.h> // in order to access printf function

int main(void) {
  printf("Hello World\n");
  return 0;
}
// source code -> compiler -> machine code(a.out & hello)

 

 

clang이라는 C언어 컴파일러를 사용해 main.c라는 C언어 파일을 컴파일한다

→ 컴파일 결과 자동으로 a.out이라는 실행파일 생성 → 실행파일이므로 machine code, 즉 0과 1로 구성된 code이다

→ .은 내가 현재 있는 위치, 현재 위치의 a.out 실행파일을 생성하기 위해 ./a.out 명령어 사용

→ clang의 -o 옵션을 두어 hello.c의 실행파일 이름을 a.out이 아닌 hello로 바꿈

→ ls 명령어로 현재 위치에 있는 여러 파일 목록 확인 가능 / rm 명령어로 원하는 특정 파일 삭제 / 다시 ls 명령어로 삭제되었는 지 확인 가능

2) various examples

① 문자열 입력받고 출력하기

#include <stdio.h>

int main(void) {

  char answer[20];
  printf("What's your name: ");
  if (scanf("%s", answer) == 1) {
    printf("Your name is %s.\n", answer);
  } else {
    printf("Failed to read your name\n");
  }
}

 

② 정수 입력받고 출력하기

#include <stdio.h>

int main(void) {
  printf("What's your age? ");

  int age;
  if (scanf("%d", &age) == 1) {
    printf("My age is %d\n", age);
  } else {
    printf("Failed to read your age\n");
  }

  int days = age * 365;

  printf("You are at least %i days old.\n", days);
  //%d and %i behavior is different in scanf
  /*
    %d assume base 10 while %i auto detects the base. Therefore, both specifiers
    behaves differently while they are used with an input specifier. So, 012
    would be 10 with %i but 12 with %d.
  */
  printf("You are at least %i days old.\n", age * 365);
}

 

③ 소수 입력받고 출력하기

#include <stdio.h>

int main(void) {
  printf("What's the price? ");

  float price;
  if (scanf("%f", &price) == 1) {
    printf("YOUR TOTAL IS is %.2f\n", price * 1.0625);
  } else {
    printf("Failed to read the price\n");
  }
}

 

④ parity 짝/홀 checking

#include <stdio.h>

int main(void) {
  printf("n : ");

  int n;
  if (scanf("%d", &n) == 1) {
    if (n % 2 == 0) {
      printf("even\n");
    } else {
      printf("odd\n");
    }

  } else {
    printf("Failed to read the number\n");
  }
}

 

⑤  for문 / if문 / while문

#include <stdio.h>

int main(void) {

  for (int counter = 0; counter < 10; counter++)
    {
      printf("hello, world\n");
    }

  int x = 10;
  int y = 20;

  if (x < y)
  {
    printf("x is less than y\n");
  }
  else
  {
    printf("x is not less than y\n");
  }

  int i = 0;
  while (i < 10)
    {
      printf("hello %d\n",i);
      i += 1;
    }
}

 

⑥ and / or operator if문

#include <stdio.h>

int main(void) {
  printf("Do you agree?\n");

  char c;
  if (scanf("%c", &c) == 1) {
    if (c == 'Y' || c == 'y') {
      printf("Agreed.\n");
    }
    else if (c == 'N' || c == 'n')
    {
      printf("Not Agreed.\n");
    }

  } else {
    printf("Failed to read the character\n");
  }
}

 

⑦ C언어는 순차적 흐름으로 코드를 읽으므로 main()를 먼저 기술하려면, 사용할 함수 먼저 선언 필요

→ 선언 안하고 main()부터 작성하면 'warning: implicit declaration of function '~(func name)' is invalid in C99' 에러 발생

#include <stdio.h>

void cough(int number_of_coughs); // func declaration
// if not declared, 'warning: implicit declaration of function 'cough' is invalid in C99' arises

int main(void) {
  printf("Enter the number of coughs ");

  int number_of_coughs;
  if (scanf("%d", &number_of_coughs) == 1) {
    cough(number_of_coughs);
  } else {
    printf("Failed to read your coughs\n");
  }
}

void cough(int number_of_coughs) {
  for (int i = 0; i < number_of_coughs; i++){
    printf("cough\n");
  }
}

 

⑧ 입력이 들어간 do-while문 / for문

#include <stdio.h>

int main(void) {
  int n;
  int cnt = 0;

  do {
    if (cnt >= 1) {
      printf("enter the width which is bigger than or equal to 1\n");
    }
    printf("enter the width : ");
    if (scanf("%d", &n) == 1) {
      if (cnt == 0) {
        cnt++;
      }
    } else {
      printf("Failed to read the width\n");
    }
  } while (n < 1);

  for (int i = 0; i < n; i++) {
    printf("?");
  }
  printf("\n");
}

/*
enter the width : 0
enter the width which is bigger than or equal to 1
enter the width : -1
enter the width which is bigger than or equal to 1
enter the width : -3
enter the width which is bigger than or equal to 1
enter the width : -5
enter the width which is bigger than or equal to 1
enter the width : 2
??
*/

 

⑨ 중첩 for문

#include <stdio.h>

int main(void) {
  int n;
  int cnt = 0;

  do {
    if (cnt >= 1) {
      printf("enter the size which is bigger than or equal to 1\n");
    }
    printf("enter the size : ");
    if (scanf("%d", &n) == 1) {
      if (cnt == 0) {
        cnt++;
      }
    } else {
      printf("Failed to read the width\n");
    }
  } while (n < 1);

  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j ++) {
      printf("#");
    }
    printf("\n");
  }
}

/*
enter the size : 10
##########
##########
##########
##########
##########
##########
##########
##########
##########
##########
*/

 

⑩ overflow / RAM

→ finite, 프로그램 저장되는 공간

 

→ 소수점을 나타낼 때 컴퓨터는 정확하게 나타내지 못한다

#include <stdio.h>

int main(void) {
  printf("Enter x and y\n");

  float x;
  float y;

  printf("x : ");
  if (scanf("%f", &x) == 1) {
  } else {
    printf("Failed to read x\n");
  }
  printf("y : ");
  if (scanf("%f", &y) == 1) {
  } else {
    printf("Failed to read y\n");
  }

  printf("x / y = %.50f\n", x / y);
}


/*
Enter x and y
x : 1

y : 10
x / y = 0.10000000149011611938476562500000000000000000000000
*/

 

→ 2를 무한대로 곱하면 정해진 자릿수에서 언젠가는 2를 곱할 때 모든 자릿수가 0이 되어 0으로 끝남

#include <stdio.h>
#include <unistd.h>

int main(void) {
  for (int i = 1; ; i *= 2)
    {
      printf("%i\n",i);
      sleep(1);
    }
}

/*
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216
33554432
67108864
134217728
268435456
536870912
1073741824
-2147483648
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
^C
*/

* 출처) <CS50 모두를 위한 컴퓨터 과학> 2. C언어

 

댓글