본문 바로가기
카테고리 없음

<C언어> 타입, 연산자, 제어문, 함수, 배열, 포인터 - 기본편 2

by 세계 최고의 AI Engineer_naknak 2023. 3. 22.

A reference is http://www.tcpschool.com/c/intro

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

Type
Variable

Variable is a memory space allocated by the program to store data.

Namely, variable is a memory space that could store data, and the data can be chaged.

 

Bit and Byte

A computer express and process all the data as binary number.

Bit is the smallest unit which is what computer use to process the data.

In this bit, only one data(0 and 1) can be stored.

Byte is consist of 8 bit, it 's also the smallest unit expressing one character.

 

*I already post about how variable is allocated to a memory space.

 

How to declear variable?

Here are examples.

int num01, num02;

double num03 = 1.23, num04 = 4.56;
Operator

Let me pass this section, because the expression of Operator in the website is so nice. So it's useless that I express this again.

But let me post example of a trinomial operator.

int num01 = 15;
int num02 = 8;
int result;  

result = (num01 > num02) ? num01 : num02;

printf("둘 중에 더 큰수는 %d입니다.\n", result);

if num01 is bigger than num02, result will return num01 but, in the opposite case, result will return num02.

 

Control Statement
what is control statement?

In a code, programmer can control a flow of the code.

For example, <if, switch, for, while, do/while, continue, break, goto>

 

Example of (if / else if / else)

int num = 7;  

if (num < 5)

{

    printf("입력하신 수는 5보다 작습니다.\n");

}

else if (num == 5)

{

    printf("입력하신 수는 5입니다.\n");

}

else

{

    printf("입력하신 수는 5보다 큽니다.\n");

}

Example of Switch Statement

int num = 2;  

switch (num)

{

    case 1:

        printf("입력하신 수는 1입니다.\n");

        break;

    case 2:

        printf("입력하신 수는 2입니다.\n");

        break;

    case 3:

        printf("입력하신 수는 3입니다.\n");

        break;

    case 4:

        printf("입력하신 수는 4입니다.\n");

        break;

    case 5:

        printf("입력하신 수는 5입니다.\n");

        break;

    default:

        printf("1부터 5까지의 수만 입력해 주세요!");

        break;

}  

// if you don't add break, the program will run below case whether u want it or not.

 

C function
What is a function?

프로그래밍에서 함수(function)란 하나의 특별한 목적의 작업을 수행하기 위해 독립적으로 설계된 프로그램 코드의 집합으로 정의할 수 있습니다.

A function in programming is a set of codes that are designed independently to perform one particular purposeful task.

 

Define a function

Let's see an example of function.

#include <stdio.h>

int bigNum(int num01, int num02) // 함수의 정의
{
    if (num01 >= num02)
    {
        return num01;
    }
    else
    {
        return num02;
    }
}

Yeah, that's it.

 

*Caution

In C, compiler runs main() at first. So, If you want to define functions, you must define after main().

 

Variable scope

In C, according to location where to variable declared, variable scope, time of memory return, initialization status, store space are changed.

 

1. 지역 변수(local variable)

2. 전역 변수(global variable)

3. 정적 변수(static variable)

4. 레지스터 변수(register variable)

 

Memory structure

메모리의 구조

OS of computer provide various memory space for running program.

This is representation of memory space which is allocated by the OS.

 

1. 코드(code) 영역

2. 데이터(data) 영역

3. 스택(stack) 영역

4. 힙(heap) 영역

From TCP School

재귀 호출(recursive call)

What is recursive call? as name is, recursive call is invoking itself again.

And for preventing stack overflow, you must add if which is put a stop on a recursive call.

int rSum(int n)
{
    if (n == 1)           // n이 1이면, 그냥 1을 반환함.
    {
          return 1;
    }
    return n + rSum(n-1); // n이 1이 아니면, n을 1부터 (n-1)까지의 합과 더한 값을 반환함.
}
Array
1D array

Array is a set which is consist of variable of same type.

And we call each value as element, in array the number that indicate location of array is called 'index'.

Index is always start from 0 and can only have positive integer.

 

int i;
int sum = 0;
int grade[3];        // 길이가 3인 int형 배열 선언  

/* 배열의 초기화 */
grade[0] = 85;       // 국어 점수
grade[1] = 65;       // 영어 점수
grade[2] = 90;       // 수학 점수  

/* 또는 int grade[3] = {85, 65, 90}; 이렇게 초기화 할 수 있습니다. */

for (i = 0; i < 3; i++)
{
    sum += grade[i]; // 인덱스를 이용한 배열의 접근
}  
printf("국영수 과목 총 점수 합계는 %d점이고, 평균 점수는 %f점입니다.\n", sum, (double)sum/3);

how to allocate array to memory

2D Array

how 2d array allocates to memory

int arr01[2][3] = {10, 20, 30, 40, 50, 60};

int arr02[2][3] = {

    {10, 20, 30},

    {40, 50, 60}

};  

arr_col_len = sizeof(arr[0]) / sizeof(arr[0][0]); // 2차원 배열의 열의 길이를 계산함
arr_row_len = (sizeof(arr) / arr_col_len) / sizeof(arr[0][0]); // 2차원 배열의 행의 길이를 계산함

 

Pointer
What is a pointer?

Before start. we should know the concept of address value.

Address value of data means the starting address of the memory where the data is stored.

In C language, these address values are represented by dividing them into 1-byte memory space.

For example, integer data has a size of 4 byte but, integer data's address value points only one byte.

 

So,

pointer is a variable which stores the address value of the memory, it is called as pointer variable.

Pointer stores address value.

int n = 100;   // 변수의 선언

int *ptr = &n; // 포인터의 선언

Example of pointer

There are two pointer operation

1. & (Reference operation)

2. *  (Dereferencing  operation)

 

주소 연산자는 변수의 이름 앞에 사용하여, 해당 변수의 주소값을 반환합니다.

& (Reference operation) uses before name of variable, it returns address value of the variable.

참조 연산자는 포인터의 이름이나 주소 앞에 사용하여, 포인터에 가리키는 주소에 저장된 값을 반환합니다.

*  (Dereferencing  operation) uses before name of pointer or address, it returns value stored in address which is pointed by pointer .

 

int x = 7;        // 변수의 선언
int *ptr = &x;    // 포인터의 선언
int *pptr = &ptr; // 포인터의 참조

** 배열 포인터 (어려운 개념이므로 한국어로 적겠습니다.)

int (*pArr)[3];

이런식으로 선언이 됩니다. 배열 포인터가 가지고 있는 첨자인 3으로 배열을 다시 쪼개서 저장한다는 논리적 구조를 가지고 있습니다.

그래서 만약에 pArr = arr01이 들어오게 되면 6개인 인자를 3개로 나눠서 다시 저장하게 됩니다(배열의 칸이 3칸으로 설정됩니다)

흥달쌤 C언어 특강 36

그래서 pArr에 arr01의 주소값(100)이 들어가고 논리적으로 pArr[0] = 100, pArr[1] = 103의 주소값이 담기게 됩니다.

*(*pArr +1) ==> 먼저 *pArr은 100입니다. 참고로 배열 포인터는 간접 연산자로 2번 접근해야 배열에 담긴 값으로 접근할 수 있습니다. 즉, *pArr == 100, *(*pArr) == 1 이 되는 것입니다. **(pArr + 1) 은 pArr[1]의 값의 값과 동일합니다.

네, 그렇습니다.

 

 

댓글