กลับไปหน้าบทความ

⚙️ ภาษา C (สอนแบบครบระดับ)

C คือรากฐานของหลายภาษา ใช้ในระบบปฏิบัติการ, embedded, และงานที่ต้องการควบคุมหน่วยความจำอย่างละเอียด

📋 เนื้อหา (พื้นฐาน)

  • 🧭 C คืออะไร
  • ⚙️ การติดตั้ง & คอมไพล์
  • 🔤 ตัวแปรและชนิดข้อมูล
  • 🧮 เงื่อนไขและลูป
  • 🧩 ฟังก์ชัน
  • 📦 Array & String
  • 🏁 สรุป
  • 📝 แบบฝึกหัด

🧭 C คืออะไร

ทำไมต้องเรียน C?

C เป็นภาษาเชิงโครงสร้าง (procedural) ที่ให้การควบคุมหน่วยความจำระดับต่ำ เป็นรากฐานของภาษาสมัยใหม่หลายภาษา

  • • ประสิทธิภาพสูง: ใกล้เคียง Assembly
  • • ควบคุม Memory: จัดการหน่วยความจำเองได้
  • • Portable: compile ได้หลาย platform
  • • รากฐาน: C++, Java, Python ล้วนได้รับอิทธิพลจาก C

C ใช้ทำอะไร?

🖥️ Operating Systems

Linux, Windows kernel

🔧 Embedded Systems

Arduino, IoT devices

🎮 Game Engines

Performance-critical code

🗄️ Databases

MySQL, PostgreSQL

Hello World

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

// #include - นำเข้า header file
// stdio.h - Standard Input/Output
// main() - จุดเริ่มต้นของโปรแกรม
// printf() - พิมพ์ข้อความ
// return 0 - โปรแกรมจบปกติ

⚙️ การติดตั้ง & คอมไพล์

ติดตั้ง Compiler

# macOS - ติดตั้ง Xcode Command Line Tools
xcode-select --install

# Linux (Ubuntu/Debian)
sudo apt update
sudo apt install build-essential

# Windows - ติดตั้ง MinGW หรือ WSL
# ดาวน์โหลด MinGW จาก mingw-w64.org

Compile & Run

# คอมไพล์พื้นฐาน
gcc main.c -o main

# รันโปรแกรม
./main          # macOS/Linux
main.exe        # Windows

# คอมไพล์พร้อม warning (แนะนำ)
gcc main.c -o main -Wall -Wextra

# คอมไพล์หลายไฟล์
gcc main.c utils.c -o program

กระบวนการ Compile

Source Code (.c)
      ↓ Preprocessor (#include, #define)
Preprocessed Code
      ↓ Compiler
Assembly Code (.s)
      ↓ Assembler
Object Code (.o)
      ↓ Linker
Executable

🔤 ตัวแปรและชนิดข้อมูล

Data Types พื้นฐาน

// Integer types
char c = 'A';           // 1 byte (-128 to 127)
short s = 100;          // 2 bytes
int i = 1000;           // 4 bytes (typically)
long l = 100000L;       // 4-8 bytes
long long ll = 10000000000LL;  // 8 bytes

// Unsigned (บวกเท่านั้น)
unsigned int ui = 4000000000;

// Floating point
float f = 3.14f;        // 4 bytes, ~7 digits precision
double d = 3.14159265;  // 8 bytes, ~15 digits precision

// Boolean (C99)
#include <stdbool.h>
bool isValid = true;

Format Specifiers

int age = 20;
float price = 99.5f;
char grade = 'A';
char name[] = "Somchai";

printf("Name: %s\n", name);      // string
printf("Age: %d\n", age);        // int
printf("Price: %.2f\n", price);  // float (2 decimal)
printf("Grade: %c\n", grade);    // char

// Common format specifiers
// %d, %i  - int
// %u      - unsigned int
// %ld     - long
// %f      - float/double
// %e      - scientific notation
// %c      - char
// %s      - string
// %p      - pointer address
// %x      - hexadecimal
// %zu     - size_t

sizeof & Constants

// ตรวจสอบขนาด
printf("int = %zu bytes\n", sizeof(int));
printf("char = %zu bytes\n", sizeof(char));
printf("double = %zu bytes\n", sizeof(double));

// Constants
#define PI 3.14159
#define MAX_SIZE 100

const int DAYS_IN_WEEK = 7;  // cannot change

// Type casting
int a = 5, b = 2;
float result = (float)a / b;  // 2.5 not 2

🧮 เงื่อนไขและลูป

if-else

int score = 78;

if (score >= 80) {
    printf("Grade: A\n");
} else if (score >= 70) {
    printf("Grade: B\n");
} else if (score >= 60) {
    printf("Grade: C\n");
} else {
    printf("Grade: F\n");
}

// Ternary operator
char *result = (score >= 50) ? "Pass" : "Fail";

switch-case

int day = 3;

switch (day) {
    case 1:
        printf("Monday\n");
        break;
    case 2:
        printf("Tuesday\n");
        break;
    case 3:
        printf("Wednesday\n");
        break;
    default:
        printf("Other day\n");
}

// Fall-through (no break)
switch (day) {
    case 6:
    case 7:
        printf("Weekend\n");
        break;
    default:
        printf("Weekday\n");
}

Loops

// for loop
for (int i = 0; i < 5; i++) {
    printf("%d ", i);  // 0 1 2 3 4
}

// while loop
int count = 0;
while (count < 3) {
    printf("count: %d\n", count);
    count++;
}

// do-while (ทำอย่างน้อย 1 ครั้ง)
int num;
do {
    printf("Enter positive number: ");
    scanf("%d", &num);
} while (num <= 0);

// break & continue
for (int i = 0; i < 10; i++) {
    if (i == 3) continue;  // ข้าม 3
    if (i == 7) break;     // หยุดที่ 7
    printf("%d ", i);      // 0 1 2 4 5 6
}

🧩 ฟังก์ชัน

Function Declaration & Definition

#include <stdio.h>

// Function declaration (prototype)
int add(int a, int b);
void greet(char name[]);
int factorial(int n);

int main() {
    printf("Sum: %d\n", add(3, 5));
    greet("Somchai");
    printf("5! = %d\n", factorial(5));
    return 0;
}

// Function definitions
int add(int a, int b) {
    return a + b;
}

void greet(char name[]) {
    printf("Hello, %s!\n", name);
}

int factorial(int n) {
    if (n <= 1) return 1;
    return n * factorial(n - 1);  // recursion
}

Pass by Value vs Reference

// Pass by value (copy)
void increment(int x) {
    x++;  // แก้ไขแค่ copy
}

// Pass by reference (pointer)
void incrementPtr(int *x) {
    (*x)++;  // แก้ไขค่าจริง
}

int main() {
    int num = 5;
    
    increment(num);
    printf("%d\n", num);  // 5 (ไม่เปลี่ยน)
    
    incrementPtr(&num);
    printf("%d\n", num);  // 6 (เปลี่ยน)
    
    return 0;
}

📦 Array & String

Arrays

// Declaration & initialization
int scores[5] = {80, 90, 85, 70, 95};
int nums[10] = {0};  // ทุกตัวเป็น 0
int arr[] = {1, 2, 3};  // size = 3

// Access elements
printf("%d\n", scores[0]);  // 80
scores[1] = 100;

// Loop through array
int sum = 0;
for (int i = 0; i < 5; i++) {
    sum += scores[i];
}
printf("Average: %.2f\n", sum / 5.0);

// 2D Array
int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
printf("%d\n", matrix[1][2]);  // 6

Strings

#include <string.h>

char name[] = "Somchai";  // null-terminated
char greeting[50];

// String functions
printf("Length: %zu\n", strlen(name));  // 7

strcpy(greeting, "Hello");  // copy
strcat(greeting, " World"); // concatenate
printf("%s\n", greeting);   // Hello World

// Compare strings
if (strcmp(name, "Somchai") == 0) {
    printf("Match!\n");
}

// Input string
char input[100];
printf("Enter name: ");
fgets(input, sizeof(input), stdin);

// Remove newline from fgets
input[strcspn(input, "\n")] = 0;

🏁 สรุป

  • ✅ C เป็นภาษาระดับกลางที่ให้ควบคุม memory ได้ดี
  • ✅ Data types: int, float, char, array
  • ✅ Control flow: if-else, switch, for, while
  • ✅ Functions: declaration, definition, recursion
  • ✅ Arrays และ Strings คือโครงสร้างข้อมูลพื้นฐาน

📝 แบบฝึกหัด

ระดับง่าย

  1. เขียนโปรแกรมรับคะแนนแล้วแสดงเกรด (A-F)
  2. เขียนโปรแกรมแสดงสูตรคูณแม่ 1-12
  3. หาผลรวมของเลข 1-100

ระดับกลาง

  1. สร้าง array ตัวเลข 5 ตัวแล้วหาค่าเฉลี่ย
  2. เขียนฟังก์ชันหาค่าสูงสุดและต่ำสุดใน array
  3. เขียนโปรแกรมกลับ string (reverse)