Leveraging Programming Languages: C Lang.

m_ngyeong·2025년 4월 7일
0

정보처리기사 이론

목록 보기
28/36
post-thumbnail

10. Leveraging Programming Languages


C Lang.

✅ 포인터와 배열

#include <stdio.h>

int main() {
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr = arr;
    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += *(ptr + i);  // 포인터로 배열 접근
    }

    printf("평균: %.2f\n", sum / 5.0);
    return 0;
}
  • sum = 10 + 20 + 30 + 40 + 50 = 150
  • sum / 5.0 = 30
  • %.2f = 30.00

    🖍️ 평균: 30.00

✅ switch-case

#include <stdio.h>

int main() {
    double a = 12.0;
    double b = 4.0;
    char op = '*';  // 연산자: +, -, *, /

    switch (op) {
        case '+':
            printf("%.2f + %.2f = %.2f\n", a, b, a + b);
            break;

        case '-':
            printf("%.2f - %.2f = %.2f\n", a, b, a - b);

        case '*':
            printf("%.2f * %.2f = %.2f\n", a, b, a * b);

        case '/':
            if (b != 0)
                printf("%.2f / %.2f = %.2f\n", a, b, a / b);
            else
                printf("0으로 나눌 수 없습니다!\n");
            break;

        default:
            printf("잘못된 연산자입니다.\n");
    }

    return 0;
}
  • break 제거 (fall-through 발생)
  • switch-case는 위에서부터 차례대로 읽어 내려오며 해당하는 구문 실행
    op=* 이기 때문에 아래 구문 실행
case '*':
printf("%.2f * %.2f = %.2f\n", a, b, a * b);
  • case '*' 구문에는 break가 없기 때문에 case '/'도 실행

🖍️
12.00 * 4.00 = 48.00
12.00 / 4.00 = 3.00

✅ 조건문 - 짝/홀

#include <stdio.h>

int main() {
    int arr[] = {3, 8, 12, 7, 6, 10, 1};
    int even[7]; // C에서는 크기 없는 배열은 선언 안됌
    int count = 0;

    int length = sizeof(arr) / sizeof(arr[0]);

    for(int i=0; i<length; i++){
        if(arr[i]%2 == 0){        // if(arr[i] % 2 != 0): 홀수만 출력
            even[count] = arr[i]; // count를 인덱스로 사용
            count ++;
        }
    } // 짝수 목록: 8 12 6 10 
    
    // 버블 정렬로 오름차순 정렬
    for (int i = 0; i < count - 1; i++) {
        for (int j = 0; j < count - i - 1; j++) {
            if (even[j] > even[j + 1]) {
                int temp = even[j];
                even[j] = even[j + 1];
                even[j + 1] = temp;
            }
        }
    } 
    
    printf("%d\n", count);
    printf("짝수 목록: ");
    for (int i = 0; i < count; i++) {
        printf("%d ", even[i]);
    }
    printf("\n");

    return 0;
}
  • if(arr[i]%2 == 0): 짝수만
  • if(arr[i] % 2 != 0): 홀수만

🖍️
4
짝수 목록: 6 8 10 12

✅ 문자 배열에서 대문자만 출력

#include <stdio.h>

int main() {
    char str[] = "HeLLoWorLD";
    int length = sizeof(str)/ sizeof(str[0]);

    for(int i=0; i<length; i++){
        char ch = str[i];
        if (ch >= 'A' && ch <= 'Z'){
            printf("%c", ch);
        }
    }
    return 0;
}

🖍️ HLLWLD


✅ 구조체 아이템 접근

#include <stdio.h>

struct Product {
    char name[10];
    int price;
};

int main() {
    struct Product items[2] = {
        {"Pen", 500},
        {"Book", 1200}
    };
    int sum = 0;
    for (int i = 0; i < 2; i++) {
        sum += items[i].price;
    }
    printf("%d\n", sum);
    return 0;
}
  • sum += items[i].price; 구조체 아이템 접근

🖍️ 1700

✅ 구조체 포인터

#include <stdio.h>

struct Point {
    int x;
    int y;
};

int main() {
    struct Point p = {3, 4};
    struct Point *ptr = &p;

    printf("%d\n", ptr->x + ptr->y);
    return 0;
}

🖍️ 7

✅ 구조체 초기화

#include <stdio.h>

struct Car {
    char name[10];
    int year;
    int price;
};

int main() {
    struct Car c = {"Sonata", 2020};
    printf("%d\n", c.price);
    return 0;
}
  • 구조체 전역/로컬 선언 시 초기값은 0, 특히 main()에서 선언된 정적 지역 변수는 보장됨

🖍️ 0

✅ 구조체 포인터를 함수로 전달

#include <stdio.h>

struct Data {
    int x;
    int y;
};

void update(struct Data *d) {
    d->x += 5;
    d->y *= 2;
}

int main() {
    struct Data d = {2, 3};
    update(&d);
    printf("%d %d\n", d.x, d.y);
    return 0;
}

🖍️ 7 6

✅ 구조체 배열과 조건 판단

#include <stdio.h>

struct Score {
    char name[10];
    int score;
};

int main() {
    struct Score list[3] = {
        {"Kim", 85},
        {"Lee", 92},
        {"Park", 78}
    };
    int count = 0;

    for (int i = 0; i < 3; i++) {
        if (list[i].score >= 80) {
            count++;
        }
    }

    printf("%d\n", count);
    return 0;
}

🖍️ 2

✅ 구조체 리턴 함수

#include <stdio.h>

struct Point {
    int x, y;
};

struct Point move(struct Point p) {
    p.x += 10;
    p.y += 10;
    return p;
}

int main() {
    struct Point p = {1, 2};
    struct Point result = move(p);
    printf("%d %d\n", result.x, result.y);
    return 0;
}

🖍️ 11 12

✅ 중첩 구조체

#include <stdio.h>

struct Date {
    int year, month, day;
};

struct Person {
    char name[20];
    struct Date birth;
};

int main() {
    struct Person p = {"Jin", {1999, 12, 5}};
    printf("%d\n", p.birth.year);
    return 0;
}

🖍️ 1999

✅ 구조체 포인터 배열

#include <stdio.h>

struct Info {
    char name[10];
    int level;
};

int main() {
    struct Info a = {"Alice", 2};
    struct Info b = {"Bob", 3};
    struct Info* arr[2] = {&a, &b};

    printf("%s %d\n", arr[1]->name, arr[0]->level);
    return 0;
}

🖍️ Bob 2

profile
ʚȉɞ

0개의 댓글