❖ 1. Introduction to C++

1.1 What is C++? រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

C++ គឺជាភាសាសរសេរកម្មវិធីកម្រិតខ្ពស់ (High-Level Programming)​ បង្កើតដោយ Bjarne Stroustrup ឆ្នាំ 1979 នៅក្រុមហ៊ុន Bell Labs ហើយវាជាការអភិវឌ្ឍពីភាសា C ដោយបន្ថែមលក្ខណៈ Object-Oriented Programming (OOP)។

C++ ត្រូវបានគេប្រើប្រាស់យ៉ាងទូលំទូលាយក្នុងការអភិវឌ្ឍន៍ៈ

1.2 Features and Benefits of C++ រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

លក្ខណៈពិសេសសំខាន់ៗរបស់ C++៖

1. Object-Oriented Programming (OOP)

C++ គាំទ្រ OOP ដែលធ្វើឱ្យយើងអាចរៀបចំកូដឱ្យមានរចនាសម្ព័ន្ធល្អ និងងាយស្រួលគ្រប់គ្រងសម្រាប់គម្រោងធំៗ។

OOP រួមបញ្ចូលទាំង៖

2. Fast and Efficient (លឿន និងមានប្រសិទ្ធភាព)

C++ ត្រូវបាន compile ទៅជា machine code ដោយផ្ទាល់ ធ្វើឱ្យវាមានល្បឿនលឿនខ្លាំង និងប្រើប្រាស់ធនធានប្រព័ន្ធបានល្អ។

3. Portability (ភាពអាចប្តូរបាន)

កូដ C++ អាចដំណើរការលើ platform ផ្សេងៗគ្នា (Windows, Linux, MacOS) ដោយមិនចាំបាច់កែប្រែច្រើន។

4. Rich Library Support (បណ្ណាល័យសម្បូរបែប)

C++ មាន Standard Template Library (STL) ដែលផ្តល់នូវ data structures និង algorithms ជាច្រើនដែលអាចប្រើបានភ្លាមៗ។

5. Memory Management (ការគ្រប់គ្រងអង្គចងចាំ)

C++ អនុញ្ញាតឲ្យគ្រប់គ្រងអង្គចងចាំតាមរយៈ pointers ដែលមានប្រសិទ្ធភាពខ្ពស់ និងការគ្រប់គ្រងកម្រិតទាប។

6. Multi-Paradigm (គាំទ្រច្រើនប្រភេទ)

C++ គាំទ្រទាំង procedural programming, object-oriented programming, និង generic programming។

1.3 History of C++ (ប្រវត្តិ C++) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Bjarne Stroustrup បានបង្កើត C++ នៅឆ្នាំ 1979 នៅក្នុងក្រុមហ៊ុន Bell Labs។ ដំបូងគាត់ហៅភាសានេះថា "C with Classes" ពីព្រោះវាគឺជាភាសា C ដែលបានបន្ថែម classes។

ប្រវត្តិសង្ខេប៖

1.4 Structure of a C++ Program (រចនាសម្ព័ន្ធនៃកម្មវិធី C++) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

មុនពេលយើងសិក្សាលម្អិត សូមពិនិត្យមើលកម្មវិធី C++ ដ៏សាមញ្ញបំផុត៖

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}

ឥឡូវនេះ សូមពន្យល់ពីផ្នែកនីមួយៗ៖

1.4.1 Meaning of #include

#include គឺជា preprocessor directive ដែលប្រាប់ឱ្យ compiler រួមបញ្ចូល header file មួយទៅក្នុងកម្មវិធី។

#include <iostream> - រួមបញ្ចូល header file ឈ្មោះ iostream ដែលមាន functions សម្រាប់ input/output operations ដូចជា cout និង cin

ឧទាហរណ៍ header files ផ្សេងទៀត៖

#include <cmath>      // សម្រាប់ mathematical functions
#include <string>     // សម្រាប់ string operations
#include <vector>     // សម្រាប់ vector container
#include <fstream>    // សម្រាប់ file operations

1.4.2 Header Files

Header files គឺជាឯកសារដែលមាន declarations នៃ functions, classes, និង variables ដែលយើងអាចប្រើក្នុងកម្មវិធី។

ប្រភេទនៃ Header Files៖

សម្គាល់: Header files របស់ Standard Library ប្រើ < > ចំណែក user-defined headers ប្រើ " "

1.4.3 Namespace (using namespace std;)

Namespace គឺជាវិធីដើម្បីរៀបចំកូដ និងការពារ naming conflicts។ std គឺជា namespace របស់ Standard Library។

ដោយគ្មាន using namespace std;

#include <iostream>

int main() {
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

ជាមួយ using namespace std;

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!" << endl;
    return 0;
}
ដំបូន្មាន: សម្រាប់គម្រោងតូច អ្នកអាចប្រើ using namespace std; ប៉ុន្តែសម្រាប់គម្រោងធំ គួរតែប្រើ std:: ដើម្បីជៀសវាងការប៉ះទង្គិចឈ្មោះ។

1.4.4 main() Function

int main() គឺជា entry point នៃកម្មវិធី C++ គ្រប់ៗកម្មវិធី។ នៅពេលដែលយើង run កម្មវិធី execution នឹងចាប់ផ្តើមពី main() function។

1.4.5 return 0;

return 0; ប្រាប់ថាកម្មវិធីបានដំណើរការបញ្ចប់ដោយជោគជ័យ។

1.5 Basic Syntax Rules (ច្បាប់ syntax មូលដ្ឋាន) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

1.5.1 Semicolon (;)

រាល់ statement ក្នុង C++ ត្រូវបញ្ចប់ដោយ semicolon (;)។

int x = 10;        // correct
cout << "Hello";   // correct
int y = 20         // ERROR - missing semicolon

1.5.2 Case Sensitivity

C++ មានលក្ខណៈ case-sensitive មានន័យថា អក្សរធំ និងអក្សរតូចមានអត្ថន័យខុសគ្នា។

int Number = 10;   // Variable ឈ្មោះ Number
int number = 20;   // Variable ឈ្មោះ number (ខុសពី Number)
int NUMBER = 30;   // Variable ឈ្មោះ NUMBER (ខុសពីទាំងពីរខាងលើ)

1.5.3 Curly Braces { }

Curly braces ប្រើដើម្បីកំណត់ block នៃកូដ។

int main() {
    // Code block របស់ main function
    if (true) {
        // Code block របស់ if statement
        cout << "True";
    }
    return 0;
}
សំខាន់: រាល់ { ត្រូវមាន } ផ្គូផ្គង។ ការខ្វះ brace នឹងបណ្តាលឱ្យមាន compilation error។

ការ Compile និង Run កម្មវិធី C++៖

លើ Windows (ប្រើ MinGW ឬ Visual Studio):

// Compile
g++ myprogram.cpp -o myprogram.exe

// Run
myprogram.exe

លើ Linux/Mac:

// Compile
g++ myprogram.cpp -o myprogram

// Run
./myprogram

1.6 Comments (អត្ថាធិប្បាយ) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Comments គឺជាអត្ថបទដែល compiler មិនយកមកដំណើរការ។ វាប្រើសម្រាប់ពន្យល់កូដឱ្យងាយយល់។

Single-line Comments (//)

ប្រើ // សម្រាប់អត្ថាធិប្បាយតែមួយបន្ទាត់។

// នេះជា comment មួយបន្ទាត់

Multi-line Comments (/* */)

ប្រើ /* */ សម្រាប់អត្ថាធិប្បាយច្រើនបន្ទាត់។

/*
   នេះជា comment ច្រើនបន្ទាត់
   អាចសរសេរច្រើនបន្ទាត់
   យ៉ាងងាយស្រួល
*/
ការប្រើ Comments ប្រកបដោយប្រសិទ្ធភាព:
  • ពន្យល់អំពីគោលបំណងនៃកូដស្មុគស្មាញ
  • បង្ហាញពីរបៀបប្រើ functions
  • កត់ចំណាំអំពីការកែប្រែនាពេលអនាគត
  • បិទកូដបណ្តោះអាសន្នសម្រាប់ការ debug

1.7 Variables & Data Types រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

1.7.1 Variables (អថេរ)

Variable គឺជាទីតាំងក្នុង memory ដែលប្រើសម្រាប់រក្សាទុកទិន្នន័យ។ រាល់ variable មានៈ

1.7.2 Variable Declaration និង Initialization

Declaration (ប្រកាស):

int age;           // ប្រកាស variable ឈ្មោះ age ប្រភេទ int
float salary;      // ប្រកាស variable ឈ្មោះ salary ប្រភេទ float
char grade;        // ប្រកាស variable ឈ្មោះ grade ប្រភេទ char

Initialization (ផ្តល់តម្លៃដំបូង):

int age = 25;              // ប្រកាស និងផ្តល់តម្លៃ
float salary = 1500.50;    // ប្រកាស និងផ្តល់តម្លៃ
char grade = 'A';          // ប្រកាស និងផ្តល់តម្លៃ

ប្រកាសច្រើន variables ក្នុងពេលតែមួយ:

int x = 10, y = 20, z = 30;
float a, b, c = 3.14;

1.7.3 Data Types (ប្រភេទទិន្នន័យ)

C++ មានប្រភេទទិន្នន័យជាច្រើន ដែលអាចបែងចែកជា៖

1. Integer Types (ប្រភេទចំនួនគត់)

Type Size Range Example
int 4 bytes -2,147,483,648 to 2,147,483,647 int age = 25;
short 2 bytes -32,768 to 32,767 short count = 100;
long 4 bytes -2,147,483,648 to 2,147,483,647 long population = 15000000;
long long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long long distance = 9876543210;

2. Floating-Point Types (ប្រភេទទសភាគ)

Type Size Precision Example
float 4 bytes ~7 digits float price = 19.99f;
double 8 bytes ~15 digits double pi = 3.14159265359;
long double 12-16 bytes ~19 digits long double precise = 3.14159265358979323846L;

3. Character Type

Type Size Range Example
char 1 byte -128 to 127 or 0 to 255 char letter = 'A';

4. Boolean Type

Type Size Values Example
bool 1 byte true or false bool isStudent = true;

5. String Type: C++ មាន string type ដែលត្រូវការ #include <string>

#include <string>
using namespace std;

string name = "Sokha";
string message = "Hello, World!";

ឧទាហរណ៍ការប្រើប្រាស់ Data Types:

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Integer types
    int age = 20;
    short year = 2024;
    long population = 16000000;
    long long bigNumber = 9876543210123456;
    
    // Floating-point types
    float price = 15.99f;
    double pi = 3.14159265359;
    
    // Character
    char grade = 'A';
    
    // Boolean
    bool isPassed = true;
    
    // String
    string name = "Dara";
    
    // បង្ហាញលទ្ធផល
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "Grade: " << grade << endl;
    cout << "Price: $" << price << endl;
    cout << "Pi: " << pi << endl;
    cout << "Passed: " << isPassed << endl;
    
    return 0;
}

1.7.4 Naming Rules for Variables

ច្បាប់សម្រាប់ការដាក់ឈ្មោះ variables:

ឧទាហរណ៍ឈ្មោះត្រឹមត្រូវ:

int studentAge;
float _price;
string firstName;
int count123;
bool isValid;

ឧទាហរណ៍ឈ្មោះមិនត្រឹមត្រូវ:

int 123count;      // ERROR - ចាប់ផ្តើមដោយលេខ
float my-price;    // ERROR - មាន hyphen
string first name; // ERROR - មាន space
int for;           // ERROR - keyword របស់ C++

1.8 Input / Output (cin / cout) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

1.8.1 Output with cout

cout (Console Output) ប្រើសម្រាប់បង្ហាញទិន្នន័យលើ screen។

Syntax:

cout << data;

ឧទាហរណ៍:

#include <iostream>
using namespace std;

int main() {
    cout << "Hello, World!";                    // បង្ហាញអត្ថបទ
    cout << endl;                                // ចុះបន្ទាត់ថ្មី
    
    int age = 20;
    cout << "Age: " << age;                     // បង្ហាញអត្ថបទ និង variable
    cout << endl;
    
    cout << "Sum: " << 10 + 20 << endl;         // បង្ហាញលទ្ធផល calculation
    
    // បង្ហាញច្រើនតម្លៃក្នុងមួយ statement
    string name = "Sok";
    int score = 95;
    cout << "Student: " << name << ", Score: " << score << endl;
    
    return 0;
}

endl vs \n:

cout << "Line 1" << endl;    // ចុះបន្ទាត់ថ្មី និង flush buffer
cout << "Line 2\n";           // ចុះបន្ទាត់ថ្មី (លឿនជាង)

1.8.2 Input with cin

cin (Console Input) ប្រើសម្រាប់ទទួលយកទិន្នន័យពីអ្នកប្រើប្រាស់។

Syntax:

cin >> variable;

ឧទាហរណ៍:

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    cout << "Your age is: " << age << endl;
    
    return 0;
}

Input ច្រើន variables:

#include <iostream>
using namespace std;

int main() {
    int day, month, year;
    cout << "Enter date (day month year): ";
    cin >> day >> month >> year;
    cout << "Date: " << day << "/" << month << "/" << year << endl;
    return 0;
}

Input String with Spaces:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string fullName;
    cout << "Enter your full name: ";
    getline(cin, fullName);  // ប្រើ getline សម្រាប់អានទាំងបន្ទាត់
    cout << "Your name: " << fullName << endl;
    return 0;
}
សំខាន់: cin ធម្មតាឈប់នៅពេលជួប whitespace (space, tab, newline)។ ប្រើ getline() ដើម្បីអាន string ដែលមាន spaces។

ឧទាហរណ៍ពេញលេញ Input/Output:

#include <iostream>
#include <string>
using namespace std;

int main() {
    // ប្រកាស variables
    string studentName;
    int studentAge;
    float studentScore;
    char studentGrade;
    
    // Input ទិន្នន័យ
    cout << "===== Student Information =====" << endl;
    cout << "Enter student name: ";
    getline(cin, studentName);
    cout << "Enter student age: ";
    cin >> studentAge;
    cout << "Enter student score: ";
    cin >> studentScore;
    cout << "Enter student grade (A/B/C/D/F): ";
    cin >> studentGrade;
    
    // Output ទិន្នន័យ
    cout << "\n===== Student Report =====" << endl;
    cout << "Name: " << studentName << endl;
    cout << "Age: " << studentAge << " years old" << endl;
    cout << "Score: " << studentScore << endl;
    cout << "Grade: " << studentGrade << endl;
    return 0;
}

លំហាត់ប្រចាំមេរៀនទី 1 - Introduction to C++

Exercise 1: សរសេរកម្មវិធី C++ ដែលបង្ហាញឈ្មោះ និងអាសយដ្ឋានរបស់អ្នកលើ screen។

Exercise 2: បង្កើតកម្មវិធីដែលប្រកាស variables សម្រាប់រក្សាទុក: ឈ្មោះ, អាយុ, កម្ពស់ (meters), និងទម្ងន់ (kg) របស់មនុស្សម្នាក់។ បន្ទាប់មកបង្ហាញពួកវា។

Exercise 3: សរសេរកម្មវិធីដែលសួរអ្នកប្រើប្រាស់អំពីឈ្មោះ និងអាយុ បន្ទាប់មកបង្ហាញ Hello [name], you are [age] years old!។

Exercise 4: បង្កើតកម្មវិធីដែលសួរពីតម្លៃ 2 ចំនួន integer បន្ទាប់មកបង្ហាញ ផលបូក, ផលដក, ផលគុណ, និងផលចែករបស់ពួកវា។

Exercise 5: សរសេរកម្មវិធីដែលគណនា BMI (Body Mass Index)។ Formula: BMI = weight(kg) / (height(m) * height(m)). អនុញ្ញាតឱ្យអ្នកប្រើប្រាស់បញ្ចូល weight និង height បន្ទាប់មកបង្ហាញ BMI។

❖ 2. Operators & Expressions in C++

2.1 What are Operators and Expressions? រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Operators (សញ្ញាប្រមាណវិធី)

Operators គឺជានិមិត្តសញ្ញាពិសេសដែលប្រាប់ឱ្យ compiler ធ្វើប្រមាណវិធី (operations) ជាក់លាក់មួយលើ operands។

ឧទាហរណ៍:

int result = 10 + 5;
// + គឺជា operator
// 10 និង 5 គឺជា operands
// 10 + 5 គឺជា expression

Expressions (កន្សោម)

Expression គឺជាបន្សំនៃ variables, values, operators, និង function calls ដែលបង្កើតជាតម្លៃមួយ។

ឧទាហរណ៍ Expressions:

5 + 3                    // Simple expression
x * y + z                // Complex expression
(a + b) / (c - d)        // Expression with parentheses
x++                      // Expression with increment operator
x > y && y < z           // Logical expression

2.2 Const Keyword រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

const keyword ប្រើដើម្បីប្រកាស constants (តម្លៃថេរ) ដែលមិនអាចផ្លាស់ប្តូរបានក្រោយពេលបាន initialize។

Syntax:

const dataType variableName = value;

ឧទាហរណ៍:

#include <iostream>
using namespace std;

int main() {
    const double PI = 3.14159;
    const int DAYS_IN_WEEK = 7;
    const string SCHOOL_NAME = "ABC High School";
    cout << "PI: " << PI << endl;
    cout << "Days in week: " << DAYS_IN_WEEK << endl;
    cout << "School: " << SCHOOL_NAME << endl;    
    return 0;
}
Convention: ជាទូទៅគេប្រើអក្សរធំទាំងអស់សម្រាប់ឈ្មោះ constants (ដូចជា PI, MAX_SIZE) ដើម្បីងាយស្រួលសម្គាល់។

អត្ថប្រយោជន៍នៃ const:

2.3 Arithmetic Operators (សញ្ញាគណិត) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Arithmetic operators ប្រើសម្រាប់ធ្វើប្រមាណវិធីគណិតវិទ្យា។

Operator Name Description Example Result
+ Addition ផលបូក 10 + 5 15
- Subtraction ផលដក 10 - 5 5
* Multiplication ផលគុណ 10 * 5 50
/ Division ផលចែក 10 / 5 2
% Modulus នៃសល់ 10 % 3 1

ឧទាហរណ៍:

#include <iostream>
using namespace std;

int main() {
    int a = 20, b = 6;
    
    cout << "a + b = " << (a + b) << endl;  // 26
    cout << "a - b = " << (a - b) << endl;  // 14
    cout << "a * b = " << (a * b) << endl;  // 120
    cout << "a / b = " << (a / b) << endl;  // 3 (integer division)
    cout << "a % b = " << (a % b) << endl;  // 2 (remainder)
    
    // Division ជាមួយ floating-point
    double x = 20.0, y = 6.0;
    cout << "x / y = " << (x / y) << endl;  // 3.33333
    
    return 0;
}
សំខាន់ - Integer Division: នៅពេលចែក integer ទាំងពីរ លទ្ធផលនឹងជា integer (កាត់ចោលផ្នែកទសភាគ)។ ប្រើ floating-point ដើម្បីទទួលបានលទ្ធផលពិតប្រាកដ។

Modulus Operator (%)

Modulus operator ផ្តល់នូវនៃសល់នៃការចែក។ វាដំណើរការតែជាមួយ integers ប៉ុណ្ណោះ។

ការប្រើប្រាស់ Modulus:

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    // ពិនិត្យថាលេខគូ ឬសេស
    if (num % 2 == 0) {
        cout << num << " is even" << endl;
    } else {
        cout << num << " is odd" << endl;
    }
    return 0;
}

2.4 Assignment Operators (សញ្ញាផ្តល់តម្លៃ) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Assignment operators ប្រើដើម្បីផ្តល់តម្លៃទៅឱ្យ variables។

Operator Example Equivalent To Description
= x = 5 x = 5 ផ្តល់តម្លៃ 5 ទៅ x
+= x += 3 x = x + 3 បូក 3 ទៅ x
-= x -= 3 x = x - 3 ដក 3 ពី x
*= x *= 3 x = x * 3 គុណ x ដោយ 3
/= x /= 3 x = x / 3 ចែក x ដោយ 3
%= x %= 3 x = x % 3 x ទទួលនៃសល់នៃការចែកដោយ 3

ឧទាហរណ៍:

#include <iostream>
using namespace std;
int main() {
    int x = 10;

    x += 5;   // x = x + 5
    cout << "After x += 5: x = " << x << endl;  // 15
    
    x -= 3;   // x = x - 3
    cout << "After x -= 3: x = " << x << endl;  // 12
    
    x *= 2;   // x = x * 2
    cout << "After x *= 2: x = " << x << endl;  // 24
    
    x /= 4;   // x = x / 4
    cout << "After x /= 4: x = " << x << endl;  // 6

    return 0;
}

2.5 Comparison Operators (សញ្ញាប្រៀបធៀប) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Comparison operators ប្រើសម្រាប់ប្រៀបធៀបតម្លៃពីរ។ លទ្ធផលគឺ boolean (true ឬ false)។

Operator Name Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5 > 3 true
< Less than 5 < 3 false
>= Greater than or equal to 5 >= 5 true
<= Less than or equal to 5 <= 3 false

ឧទាហរណ៍:

#include <iostream>
using namespace std;

int main() {
    int a = 10, b = 20;
    
    cout << "a = " << a << ", b = " << b << endl;
    cout << "a == b: " << (a == b) << endl;  // 0 (false)
    cout << "a != b: " << (a != b) << endl;  // 1 (true)
    cout << "a > b: " << (a > b) << endl;    // 0 (false)
    cout << "a < b: " << (a < b) << endl;    // 1 (true)
    cout << "a >= b: " << (a >= b) << endl;  // 0 (false)
    cout << "a <= b: " << (a <= b) << endl;  // 1 (true)
    
    return 0;
}
សំខាន់: កុំច្រឡំ == (comparison) ជាមួយ = (assignment)!
  • x == 5 - ពិនិត្យថា x ស្មើ 5 (true/false)
  • x = 5 - ផ្តល់តម្លៃ 5 ទៅ x

2.6 Logical Operators (សញ្ញាតក្ក) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Logical operators ប្រើសម្រាប់បញ្ចូលគ្នានូវលក្ខខណ្ឌច្រើន។

Operator Name Description Example Result
&& AND ពិត ប្រសិនបើទាំងពីរខាងពិត true && false false
|| OR ពិត ប្រសិនបើមួយណាពិត true || false true
! NOT បញ្ច្រាស់តម្លៃ !true false

Truth Tables

AND (&&) Operator:

A B A && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR (||) Operator:

A B A || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

NOT (!) Operator:

A !A
truefalse
falsetrue

ឧទាហរណ៍:

#include <iostream>
using namespace std;
int main() {

    // AND operator (&&)
    int age = 20;
    bool hasID = true;
    if (age >= 18 && hasID) {
        cout << "You can enter the club" << endl;
    }
    
    // OR operator (||)
    bool isWeekend = false;
    bool isHoliday = true;
    if (isWeekend || isHoliday) {
        cout << "You can relax today!" << endl;
    }
    
    bool isRaining = false; // NOT operator (!)
    if (!isRaining) {
        cout << "You can go outside" << endl;
    }
    
    return 0;
}

2.7 Increment and Decrement Operators (++ --) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Increment និង Decrement operators ប្រើសម្រាប់បន្ថែម ឬដក 1 ពី variable។

Operator Name Description Example
++x Pre-increment បន្ថែមមុន បន្ទាប់មកប្រើ ++x
x++ Post-increment ប្រើមុន បន្ទាប់មកបន្ថែម x++
--x Pre-decrement ដកមុន បន្ទាប់មកប្រើ --x
x-- Post-decrement ប្រើមុន បន្ទាប់មកដក x--

ឧទាហរណ៍:

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 5;
    
    cout << "Initial: a = " << a << ", b = " << b << endl;
    
    // Pre-increment
    cout << "++a = " << ++a << endl;  // បង្ហាញ 6, a = 6
    cout << "a = " << a << endl;      // a = 6
    
    // Post-increment
    cout << "b++ = " << b++ << endl;  // បង្ហាញ 5, b = 6
    cout << "b = " << b << endl;      // b = 6
    
    // Pre-decrement
    cout << "--a = " << --a << endl;  // បង្ហាញ 5, a = 5
    
    // Post-decrement
    cout << "b-- = " << b-- << endl;  // បង្ហាញ 6, b = 5
    
    return 0;
}

ភាពខុសគ្នារវាង Pre និង Post:

#include <iostream>
using namespace std;

int main() {
    int x = 5;
    int y = ++x;  // Pre-increment: x = 6, y = 6
    
    int a = 5;
    int b = a++;  // Post-increment: a = 6, b = 5
    
    cout << "x = " << x << ", y = " << y << endl;
    cout << "a = " << a << ", b = " << b << endl;
    
    return 0;
}

លំហាត់ប្រចាំមេរៀនទី 2 - Operators & Expressions

Exercise 1: សរសេរកម្មវិធីគណនា area និង perimeter នៃចតុកោណកែង។ អនុញ្ញាតឱ្យអ្នកប្រើប្រាស់បញ្ចូល length និង width។

Exercise 2: បង្កើតកម្មវិធីបម្លែងសីតុណ្ហភាពពី Celsius ទៅ Fahrenheit។ Formula: F = (C * 9/5) + 32។

Exercise 3: សរសេរកម្មវិធីពិនិត្យមើលថាលេខមួយជាលេខគូ ឬលេខសេសដោយប្រើ modulus operator។

Exercise 4: បង្កើតកម្មវិធីដែលទទួល 3 លេខ និងពិនិត្យថាលេខទី 1 ស្ថិតរវាងលេខទី 2 និង 3 ដែរឬទេ (ប្រើ logical operators)។

Exercise 5: សរសេរកម្មវិធីគណនា compound interest។ Formula: A = P(1 + r/n)^(nt) ដែល P = principal, r = rate, n = compound frequency, t = time។

Exercise 6: សរសេរកម្មវិធី C++ ដើម្បីបញ្ចូលលេខ ២ ហើយគណនា បូក (+), ដក (-), គុណ (*), ចែក (/) និង modulus (%) រវាងលេខទាំងពីរ បង្ហាញលទ្ធផលទាំងអស់លើ screen។

Exercise 7: សរសេរកម្មវិធី C++ ដើម្បីបញ្ចូលលេខ ១ ហើយប្រើ increment (++) និង decrement (--) operator បង្ហាញតម្លៃមុន និងបន្ទាប់ពីប្រើ operator។

Exercise 8: សរសេរកម្មវិធី C++ ដើម្បីបញ្ចូលលេខ ២ ហើយប្រៀបធៀបដោយប្រើ relational operators (>, <, >=, <=, ==, !=) បង្ហាញលទ្ធផលជា true ឬ false។

Exercise 9: សរសេរកម្មវិធី C++ ដើម្បីបញ្ចូលលេខ ១ ហើយគណនាតម្លៃដោយប្រើ assignment operators ដូចជា: +=, -=, *=, /=, %= រួចបង្ហាញលទ្ធផលបន្ទាប់ពីប្រើ operator នីមួយៗ។

Exercise 10: សរសេរកម្មវិធី C++ ដើម្បីបញ្ចូលលេខ ២ (a និង b) ហើយគណនាអំពី expression ខាងក្រោម៖
១. (a + b) * 2
២. a * a + 2 * a * b + b * b
៣. (a - b) / (a + b) រួចធ្វើការបង្ហាញលទ្ធផលនីមួយៗលើ screen។

❖ 3. Mathematical Functions in C++

3.1 Header <cmath> រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

C++ ផ្តល់នូវ mathematical functions ជាច្រើនក្នុង <cmath> header file។ ដើម្បីប្រើ functions ទាំងនេះ យើងត្រូវរួមបញ្ចូល header នេះ។

#include <cmath>

ឧទាហរណ៍មូលដ្ឋាន:

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double num = 16.0;
    double result = sqrt(num);  // ការ៉េ 16
    
    cout << "Square root of " << num << " is " << result << endl;
    
    return 0;
}

3.2 Basic Mathematical Functions រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

3.2.1 sqrt() - Square Root (ការ៉េ)

ផ្តល់នូវការ៉េនៃលេខ។

Syntax: double sqrt(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double numbers[] = {4, 9, 16, 25, 2};
    
    for (int i = 0; i < 5; i++) {
        cout << "sqrt(" << numbers[i] << ") = " 
             << sqrt(numbers[i]) << endl;
    }
    
    return 0;
}

// Output:
// sqrt(4) = 2
// sqrt(9) = 3
// sqrt(16) = 4
// sqrt(25) = 5
// sqrt(2) = 1.41421

3.2.2 pow() - Power (ស្វ័យគុណ)

គណនា x រំលេក y (x^y)។

Syntax: double pow(double x, double y)

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    cout << "2^3 = " << pow(2, 3) << endl;      // 8
    cout << "5^2 = " << pow(5, 2) << endl;      // 25
    cout << "10^0 = " << pow(10, 0) << endl;    // 1
    cout << "4^0.5 = " << pow(4, 0.5) << endl;  // 2 (same as sqrt(4))
    cout << "2^-1 = " << pow(2, -1) << endl;    // 0.5
    
    return 0;
}

3.2.3 abs() - Absolute Value (តម្លៃដាច់ខាត)

ផ្តល់នូវតម្លៃដាច់ខាតនៃលេខ (តម្លៃវិជ្ជមាន)។

Syntax:

#include <iostream>
#include <cmath>
using namespace std;
int main() {
    int a = -10;
    double b = -15.5;
    
    cout << "abs(" << a << ") = " << abs(a) << endl;      // 10
    cout << "fabs(" << b << ") = " << fabs(b) << endl;    // 15.5
    
    // ឧទាហរណ៍ការប្រើ: រកចម្ងាយរវាងពីរចំណុច
    int point1 = 5, point2 = -3;
    int distance = abs(point1 - point2);
    cout << "Distance: " << distance << endl;  // 8
    
    return 0;
}

3.2.4 ceil() - Ceiling (បង្គត់ឡើងលើ)

បង្គត់លេខទៅជាលេខគត់ដែលធំជាងឬស្មើ (បង្គត់ឡើងលើ)។

Syntax: double ceil(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "ceil(4.2) = " << ceil(4.2) << endl;    // 5
    cout << "ceil(4.8) = " << ceil(4.8) << endl;    // 5
    cout << "ceil(-4.2) = " << ceil(-4.2) << endl;  // -4
    cout << "ceil(5.0) = " << ceil(5.0) << endl;    // 5
    return 0;
}

3.2.5 floor() - Floor (បង្គត់ចុះក្រោម)

បង្គត់លេខទៅជាលេខគត់ដែលតូចជាងឬស្មើ (បង្គត់ចុះក្រោម)។

Syntax: double floor(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "floor(4.2) = " << floor(4.2) << endl;    // 4
    cout << "floor(4.8) = " << floor(4.8) << endl;    // 4
    cout << "floor(-4.2) = " << floor(-4.2) << endl;  // -5
    cout << "floor(5.0) = " << floor(5.0) << endl;    // 5
    
    return 0;
}

3.2.6 round() - Round (បង្គត់ទៅជិតបំផុត)

បង្គត់លេខទៅជាលេខគត់ដែលជិតបំផុត។

Syntax: double round(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "round(4.2) = " << round(4.2) << endl;    // 4
    cout << "round(4.5) = " << round(4.5) << endl;    // 5
    cout << "round(4.8) = " << round(4.8) << endl;    // 5
    cout << "round(-4.5) = " << round(-4.5) << endl;  // -5
    
    return 0;
}
សម្គាល់: សម្រាប់ 0.5 ពិតប្រាកដ round() បង្គត់ទៅលេខគូដែលជិតបំផុត (banker's rounding) ក្នុង C++ standard លើកក្រោយ។

ឧទាហរណ៍ - Basic Math Functions:

#include <iostream>
#include <cmath>
#include <iomanip>  // សម្រាប់ setprecision
using namespace std;
int main() {
    double num;
    cout << "Enter a number: "; cin >> num;
    cout << fixed << setprecision(2);  // បង្ហាញ 2 ខ្ទង់ទសភាគ
    cout << "\n===== Math Functions Results =====" << endl;
    cout << "Original number: " << num << endl;
    cout << "Square root: " << sqrt(num) << endl;
    cout << "Square (num^2): " << pow(num, 2) << endl;
    cout << "Cube (num^3): " << pow(num, 3) << endl;
    cout << "Absolute value: " << fabs(num) << endl;
    cout << "Floor: " << floor(num) << endl;
    cout << "Rounded: " << round(num) << endl;
    return 0;
}

3.3 Trigonometric Functions (អនុគមន៍ត្រីកោណមាត្រ) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

C++ ផ្តល់អនុគមន៍ត្រីកោណមាត្រដែលប្រើ radians (មិនមែន degrees)។

សំខាន់: អនុគមន៍ត្រីកោណមាត្រប្រើ radians! ដើម្បីបម្លែង:
radians = degrees × π / 180
degrees = radians × 180 / π

3.3.1 sin() - Sine

Syntax: double sin(double x) ដែល x ជា radians

3.3.2 cos() - Cosine

Syntax: double cos(double x) ដែល x ជា radians

3.3.3 tan() - Tangent

Syntax: double tan(double x) ដែល x ជា radians

ឧទាហរណ៍:

#include <iostream>
#include <cmath>
#include <iomanip> // សម្រាប់ setprecision() កំណត់ចំនួនខ្ទង់ទសភាគ
using namespace std;

int main() {
    const double PI = 3.14159265359;
    double degrees;
    
    cout << "Enter angle in degrees: ";
    cin >> degrees;
    
    // បម្លែងពី degrees ទៅ radians
    double radians = degrees * PI / 180.0;
    
    cout << fixed << setprecision(4);
    cout << "\nAngle: " << degrees << " degrees = " << radians << " radians" << endl;

    cout << "sin(" << degrees << "°) = " << sin(radians) << endl;
    cout << "cos(" << degrees << "°) = " << cos(radians) << endl;
    cout << "tan(" << degrees << "°) = " << tan(radians) << endl;
    
    return 0;
}

Inverse Trigonometric Functions:

3.4 Exponential & Logarithmic Functions រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

3.4.1 exp() - Exponential (e^x)

គណនា e រំលេក x (e^x) ដែល e ≈ 2.71828

Syntax: double exp(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "e^0 = " << exp(0) << endl;    // 1
    cout << "e^1 = " << exp(1) << endl;    // 2.71828
    cout << "e^2 = " << exp(2) << endl;    // 7.38906
    cout << "e^-1 = " << exp(-1) << endl;  // 0.367879
    
    return 0;
}

3.4.2 log() - Natural Logarithm (ln)

គណនា logarithm base e (natural logarithm)

Syntax: double log(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "ln(1) = " << log(1) << endl;      // 0
    cout << "ln(e) = " << log(exp(1)) << endl; // 1
    cout << "ln(10) = " << log(10) << endl;    // 2.30259
    
    return 0;
}

3.4.3 log10() - Base-10 Logarithm

គណនា logarithm base 10

Syntax: double log10(double x)

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    cout << "log10(1) = " << log10(1) << endl;       // 0
    cout << "log10(10) = " << log10(10) << endl;     // 1
    cout << "log10(100) = " << log10(100) << endl;   // 2
    cout << "log10(1000) = " << log10(1000) << endl; // 3
    
    return 0;
}

តារាងសង្ខេប Math Functions:

Function Description Example Result
sqrt(x) ការ៉េ sqrt(16) 4
pow(x, y) x រំលេក y pow(2, 3) 8
abs(x) តម្លៃដាច់ខាត (int) abs(-5) 5
fabs(x) តម្លៃដាច់ខាត (double) fabs(-5.5) 5.5
ceil(x) បង្គត់ឡើងលើ ceil(4.2) 5
floor(x) បង្គត់ចុះក្រោម floor(4.8) 4
round(x) បង្គត់ជិតបំផុត round(4.5) 5
sin(x) Sine (radians) sin(0) 0
cos(x) Cosine (radians) cos(0) 1
tan(x) Tangent (radians) tan(0) 0
exp(x) e^x exp(1) 2.71828
log(x) ln(x) log(10) 2.30259
log10(x) log₁₀(x) log10(100) 2

លំហាត់ប្រចាំមេរៀនទី 3 - Mathematical Functions

Exercise 1: សរសេរកម្មវិធីគណនា hypotenuse នៃត្រីកោណកែង (right triangle) ដោយប្រើ Pythagorean theorem: c = √(a² + b²)។

Exercise 2: បង្កើតកម្មវិធីគណនាផ្ទៃ និងបរិមាត្រនៃរង្វង់ពី radius ដែលបានផ្តល់ឱ្យ។ ប្រើ π = 3.14159។

Exercise 3: សរសេរកម្មវិធីគណនាចម្ងាយរវាង 2 ចំណុចក្នុង 2D coordinate system ដោយប្រើ distance formula: d = √((x₂-x₁)² + (y₂-y₁)²)។

Exercise 4: បង្កើត program ដែលគណនា sin, cos, និង tan សម្រាប់មុំពី 0° ដល់ 90° (រៀងរាល់ 15°) និងបង្ហាញលទ្ធផលក្នុងតារាង។

Exercise 5: សរសេរកម្មវិធី scientific calculator ដែលអនុញ្ញាតឱ្យអ្នកប្រើប្រាស់ជ្រើសរើស operation (sqrt, pow, sin, cos, tan, log, exp) និងគណនាលទ្ធផល។

❖ 4. Control Structures in C++

Control Structures គឺជាសេចក្តីបង្គាប់ដែលគ្រប់គ្រងលំដាប់នៃការប្រតិបត្តិ (execution flow) នៃកម្មវិធី។ វាអនុញ្ញាតឱ្យកម្មវិធីធ្វើការសម្រេចចិត្ត និងធ្វើការដដែលៗ។

Control Structures មាន 3 ប្រភេទសំខាន់ៗ៖

4.1 Sequence Control Structure រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Sequence Control Structure (ឬហៅថា Sequential Control Structure) គឺជារចនាសម្ព័ន្ធគ្រប់គ្រងដែលប្រតិបត្តិ statements តាមលំដាប់ពីលើទៅក្រោម គ្មានការលោត ឬរំលង។

ឈ្មោះផ្សេងទៀត:
  • Sequence Control Structure
  • Sequential Control Structure
  • Linear Control Flow

Execution Flow (លំហូរការប្រតិបត្តិ)

ក្នុង Sequence Control Structure:

Flowchart: Sequence Control Structure
StartStatement 1Statement 2Statement 3End

📌 ប្រតិបត្តិពីលើទៅក្រោម រហូតដល់ END

Statement Order (លំដាប់ statement)

លំដាប់នៃ statements មានសារៈសំខាន់ណាស់។ ការផ្លាស់ប្តូរលំដាប់អាចផ្លាស់ប្តូរលទ្ធផល។

#include <iostream>
using namespace std;

int main() {
    // Example 1: Correct sequence
    int x = 5;
    int y = 10;
    int sum = x + y;
    cout << "Sum: " << sum << endl;  // Output: 15
    
    // Example 2: Order matters
    int a = 3;
    int b = a * 2;  // b = 6
    a = 10;         // a = 10
    // b នៅតែ 6 ព្រោះវាត្រូវបានគណនាមុនពេល a ត្រូវបានផ្លាស់ប្តូរ
    
    return 0;
}

Expression Evaluation (ការវាយតម្លៃកន្សោម)

Expressions ត្រូវបានវាយតម្លៃតាមលំដាប់អាទិភាព (precedence) របស់ operators។

#include <iostream>
using namespace std;

int main() {
    int result;
    
    // លំដាប់អាទិភាព: *, / មុន +, -
    result = 2 + 3 * 4;        // 2 + 12 = 14 (មិនមែន 20)
    cout << result << endl;
    
    // ប្រើវង់ក្រចកដើម្បីប្តូរលំដាប់
    result = (2 + 3) * 4;      // 5 * 4 = 20
    cout << result << endl;
    
    // Expression ស្មុគស្មាញ
    int a = 5, b = 10, c = 2;
    result = a + b * c - a / c;  // 5 + 20 - 2 = 23
    cout << result << endl;
    
    return 0;
}

ឧទាហរណ៍ពេញលេញ - Sequence Control Structure:

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Program គណនាពន្ធ និងតម្លៃសរុប
    
    // Input
    double price;
    cout << "Enter product price: $";
    cin >> price;
    
    // Processing (តាមលំដាប់)
    double taxRate = 0.10;           // 10% tax
    double taxAmount = price * taxRate;
    double totalPrice = price + taxAmount;
    double discount = 0;
    
    // ពិនិត្យ discount (ដោយនៅតែធ្វើតាមលំដាប់)
    if (price > 100) {
        discount = totalPrice * 0.05;  // 5% discount
        totalPrice = totalPrice - discount;
    }
    
    // Output
    cout << "\n===== Receipt =====" << endl;
    cout << "Original Price: $" << price << endl;
    cout << "Tax (10%): $" << taxAmount << endl;
    cout << "Discount: $" << discount << endl;
    cout << "Total Price: $" << totalPrice << endl;
    
    return 0;
}

4.2 Conditional Control Structure រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Selection Control Structure គឺជារចនាសម្ព័ន្ធដែលអនុញ្ញាតឱ្យកម្មវិធីធ្វើការសម្រេចចិត្ត និងជ្រើសរើសផ្លូវប្រតិបត្តិផ្សេងៗគ្នា ដោយផ្អែកលើលក្ខខណ្ឌ។

ឈ្មោះផ្សេងទៀត:
  • Selection Control Structure
  • Decision Control Structure
  • Conditional Control Structure
  • Branching Statement

4.2.1 if Statement

if statement ប្រើសម្រាប់ប្រតិបត្តិកូដ ប្រសិនបើលក្ខខណ្ឌជា true។

Syntax:

if (condition) {
    // code ប្រតិបត្តិ ប្រសិនបើ condition ជា true
}
Flowchart: if Statement
StartCondition?YesExecute statementEndNo
#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;
    
    if (age >= 18) {
        cout << "You are an adult." << endl;
        cout << "You can vote!" << endl;
    }
    
    cout << "Program ends." << endl;
    
    return 0;
}

4.2.2 if-else Statement

if-else statement ប្រើសម្រាប់ប្រតិបត្តិកូដមួយ ប្រសិនបើលក្ខខណ្ឌជា true និងកូដផ្សេងទៀត ប្រសិនបើលក្ខខណ្ឌជា false។

Syntax:

if (condition) {
    // code ប្រតិបត្តិ ប្រសិនបើ condition ជា true
} else {
    // code ប្រតិបត្តិ ប្រសិនបើ condition ជា false
}
Flowchart: if-else Statement
StartCondition?YesNoif blockelse blockEnd
#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter a number: ";
    cin >> num;
    
    if (num % 2 == 0) {
        cout << num << " is EVEN" << endl;
    } else {
        cout << num << " is ODD" << endl;
    }
    
    return 0;
}

4.2.3 if-else if-else Statement

if-else if-else statement ប្រើសម្រាប់ពិនិត្យលក្ខខណ្ឌច្រើន។

Syntax:

if (condition1) {
    // code ប្រតិបត្តិ ប្រសិនបើ condition1 ជា true
} else if (condition2) {
    // code ប្រតិបត្តិ ប្រសិនបើ condition2 ជា true
} else if (condition3) {
    // code ប្រតិបត្តិ ប្រសិនបើ condition3 ជា true
} else {
    // code ប្រតិបត្តិ ប្រសិនបើគ្មានលក្ខខណ្ឌណាមួយជា true
}
Flowchart: if – else if – else Statement
StartCondition 1?YesCode 1NoCondition 2?YesCode 2NoElse CodeEnd

📌 ពិនិត្យ Condition 1 → ប្រសិនបើ FALSE ពិនិត្យ Condition 2 → ប្រសិនបើ FALSE ទៅ else

#include <iostream>
using namespace std;

int main() {
    int score;
    cout << "Enter your score (0-100): ";
    cin >> score;
    
    if (score >= 90) {
        cout << "Grade: A (Excellent!)" << endl;
    } else if (score >= 80) {
        cout << "Grade: B (Very Good)" << endl;
    } else if (score >= 70) {
        cout << "Grade: C (Good)" << endl;
    } else if (score >= 60) {
        cout << "Grade: D (Pass)" << endl;
    } else {
        cout << "Grade: F (Fail)" << endl;
    }
    
    return 0;
}

4.2.4 switch Statement

switch statement ប្រើសម្រាប់ពិនិត្យតម្លៃច្រើនដ៏ជាក់លាក់។ វាងាយស្រួលអាននិងប្រើប្រសិនបើមានករណីច្រើន។

Syntax:

switch (expression) {
    case value1:
        // code សម្រាប់ value1
        break;
    case value2:
        // code សម្រាប់ value2
        break;
    case value3:
        // code សម្រាប់ value3
        break;
    default:
        // code ប្រសិនបើគ្មាន case ណាមួយត្រូវ
}
Flowchart: switch Statement
Startcase 1?YesCode 1breakNocase 2?YesCode 2breakNoDefaultEnd
សំខាន់: កុំភ្លេច break statement! ដោយគ្មាន break កម្មវិធីនឹងបន្តប្រតិបត្តិ case បន្ទាប់ទៀត (fall-through behavior)។

ឧទាហរណ៍ - Menu Selection:

#include <iostream>
using namespace std;

int main() {
    int choice;
    
    cout << "======== Menu ========" << endl;
    cout << " 1. Addition(+)       " << endl;
    cout << " 2. Subtraction(-)    " << endl;
    cout << " 3. Multiplication(*) " << endl;
    cout << " 4. Division(/)       " << endl;
    cout << "Enter your choice: ";
    cin >> choice;
    
    double a, b, result;
    
    switch (choice) {
        case 1:
            cout << "Enter two numbers: ";
            cin >> a >> b;
            result = a + b;
            cout << "Result: " << result << endl;
            break;
            
        case 2:
            cout << "Enter two numbers: ";
            cin >> a >> b;
            result = a - b;
            cout << "Result: " << result << endl;
            break;
            
        case 3:
            cout << "Enter two numbers: ";
            cin >> a >> b;
            result = a * b;
            cout << "Result: " << result << endl;
            break;
            
        case 4:
            cout << "Enter two numbers: ";
            cin >> a >> b;
            if (b != 0) {
                result = a / b;
                cout << "Result: " << result << endl;
            } else {
                cout << "Error: Division by zero!" << endl;
            }
            break;
            
        default:
            cout << "Invalid choice!" << endl;
    }
    
    return 0;
}

ឧទាហរណ៍ - Days of the Week:

#include <iostream>
using namespace std;

int main() {
    int day;
    cout << "Enter day number (1-7): ";
    cin >> day;
    
    switch (day) {
        case 1:
            cout << "Monday" << endl;
            break;
        case 2:
            cout << "Tuesday" << endl;
            break;
        case 3:
            cout << "Wednesday" << endl;
            break;
        case 4:
            cout << "Thursday" << endl;
            break;
        case 5:
            cout << "Friday" << endl;
            break;
        case 6:
            cout << "Saturday" << endl;
            break;
        case 7:
            cout << "Sunday" << endl;
            break;
        default:
            cout << "Invalid day number!" << endl;
    }
    
    return 0;
}

4.3 Loop Control Structure រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Iteration Control Structure (Loop) គឺជារចនាសម្ព័ន្ធដែលអនុញ្ញាតឱ្យកម្មវិធីធ្វើកូដដដែលៗច្រើនដង ដោយផ្អែកលើលក្ខខណ្ឌ។

ឈ្មោះផ្សេងទៀត:
  • Iteration Control Structure
  • Loop Control Structure
  • Looping Control Structure
  • Repetition Control Structure

C++ មាន loop 3 ប្រភេទ៖

4.3.1 for Loop

for loop ប្រើនៅពេលយើងដឹងចំនួនដងដែលត្រូវធ្វើដដែលៗ។

Syntax:

for (initialization; condition; increment/decrement) {
    // code ត្រូវធ្វើដដែលៗ
}
Flowchart: for Loop
Starti = 0i &lt; 10?YesExecute Loop Body + i++Loop backNoEnd
#include <iostream>
using namespace std;

int main() {
    // បង្ហាញលេខពី 1 ដល់ 10
    for (int i = 1; i <= 10; i++) {
        cout << i << " ";
    }
    cout << endl;
    
    return 0;
}
// Output: 1 2 3 4 5 6 7 8 9 10

ឧទាហរណ៍ - គណនាផលបូក:

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0;
    
    cout << "Enter a number: ";
    cin >> n;
    
    // គណនាផលបូកពី 1 ដល់ n
    for (int i = 1; i <= n; i++) {
        sum += i;  // sum = sum + i
    }
    
    cout << "Sum from 1 to " << n << " = " << sum << endl;
    
    return 0;
}

ឧទាហរណ៍ - Multiplication Table:

#include <iostream>
using namespace std;

int main() {
    int num;
    
    cout << "Enter a number: ";
    cin >> num;
    
    cout << "\n===== Multiplication Table of " << num << " =====" << endl;
    
    for (int i = 1; i <= 10; i++) {
        cout << num << " x " << i << " = " << (num * i) << endl;
    }
    
    return 0;
}

4.3.2 while Loop

while loop ប្រើនៅពេលយើងមិនដឹងចំនួនដងជាមុន។ វាពិនិត្យលក្ខខណ្ឌមុនពេលប្រតិបត្តិ។

Syntax:

while (condition) {
    // code ត្រូវធ្វើដដែលៗ
}
Flowchart: while Loop
StartCondition?YesLoop BodyLoop backNoEnd

📌 ពិនិត្យ Condition មុន → ប្រសិនបើ FALSE ពីដំបូង Loop Body មិនប្រតិបត្តិ (0 ដង)

#include <iostream>
using namespace std;

int main() {
    int i = 1;

    while (i <= 5) {
        cout << i << " ";
        i++;  // សំខាន់ណាស់! បើមិនមាន loop នឹងមិនបញ្ចប់
    }
    cout << endl;

    return 0;
}
// Output: 1 2 3 4 5

4.3.3 do-while Loop

do-while loop ដូច while loop តែវាពិនិត្យលក្ខខណ្ឌបន្ទាប់ពីប្រតិបត្តិ។ ដូច្នេះវាប្រតិបត្តិយ៉ាងហោចណាស់ម្តង។

Syntax:

do {
    // code ត្រូវធ្វើដដែលៗ
} while (condition);
Flowchart: do-while Loop
StartExecute Loop Body (do)Condition? (while)YesNoEnd

⚠️ Loop Body ប្រតិបត្តិមុន → ពិនិត្យ Condition ក្រោយ → យ៉ាងហោចណាស់ 1 ដង!

#include <iostream>
using namespace std;

int main() {
    int choice;
    
    do {
        cout << "\n===== Menu =====" << endl;
        cout << "1. Say Hello" << endl;
        cout << "2. Display Date" << endl;
        cout << "3. Exit" << endl;
        cout << "Enter choice: ";
        cin >> choice;
        
        switch (choice) {
            case 1:
                cout << "Hello, User!" << endl;
                break;
            case 2:
                cout << "Today is a beautiful day!" << endl;
                break;
            case 3:
                cout << "Goodbye!" << endl;
                break;
            default:
                cout << "Invalid choice!" << endl;
        }
    } while (choice != 3);
    return 0;
}

ប្រៀបធៀប Loop Types:

Feature for Loop while Loop do-while Loop
ពេលប្រើ ចំនួនដងដឹងជាមុន ចំនួនដងមិនដឹង ត្រូវការ execute យ៉ាងហោចណាស់ 1x
ពិនិត្យលក្ខខណ្ឌ មុនពេល execute មុនពេល execute បន្ទាប់ពី execute
Minimum Execution 0 times 0 times 1 time
Syntax for (init;cond;incr) while (condition) do { } while (cond);
ឧទាហរណ៍ Loop through array User input validation Menu systems
ការជ្រើសរើស Loop:
  • for loop: ប្រើនៅពេលអ្នកដឹងថាត្រូវធ្វើដដែលៗប៉ុន្មានដង (ឧទាហរណ៍ 10 ដង, ដល់ទីបញ្ចប់ array)
  • while loop: ប្រើនៅពេលអ្នកមិនដឹងចំនួនដង ហើយលក្ខខណ្ឌអាចមិន true ពីដំបូង
  • do-while loop: ប្រើនៅពេលអ្នកត្រូវការ execute យ៉ាងហោចណាស់ម្តង (ឧទាហរណ៍ menus, user prompts)

4.3.4 Loop Control Statements

break Statement

break ប្រើដើម្បីចេញពី loop ភ្លាមៗ។

Flowchart: break Statement
StartLoop Condition?YesBreak?YesBREAK!NoLoop Body ContinuesLoop backEndNo
Flowchart: continue Statement
StartLoop Condition?YesContinue Condition?YesCONTINUE!Skip to NextNoLoop Body ContinuesLoop backEndNo

continue → រំលងផ្នែកនៃសល់នៃ iteration ហើយត្រឡប់ទៅ loop condition ភ្លាម

#include <iostream>
using namespace std;

int main() {
    int age;
    bool hasLicense;
    
    cout << "Enter your age: ";
    cin >> age;
    
    if (age >= 18) {
        cout << "Do you have a license? (1=Yes, 0=No): ";
        cin >> hasLicense;
        
        if (hasLicense) {
            cout << "You can drive!" << endl;
        } else {
            cout << "You need a license to drive." << endl;
        }
    } else {
        cout << "You are too young to drive." << endl;
    }
    
    return 0;
}

4.4.2 Nested Loops (loop ក្នុង loop)

Loop មួយអាចស្ថិតក្នុង loop មួយទៀត។ គេហៅថា nested loops។

ឧទាហរណ៍ - ត្រង្គម:

#include <iostream>
using namespace std;

int main() {
    int rows, cols;
    
    cout << "Enter number of rows: ";
    cin >> rows;
    cout << "Enter number of columns: ";
    cin >> cols;
    
    for (int i = 1; i <= rows; i++) {
        for (int j = 1; j <= cols; j++) {
            cout << "* ";
        }
        cout << endl;
    }
    
    return 0;
}

// ប្រសិនបើ rows=3, cols=5:
// * * * * *
// * * * * *
// * * * * *

ឧទាហរណ៍ - Multiplication Table 1-10:

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << "===== Multiplication Table (1-10) =====" << endl;
    
    for (int i = 1; i <= 10; i++) {
        for (int j = 1; j <= 10; j++) {
            cout << setw(4) << (i * j);
        }
        cout << endl;
    }
    
    return 0;
}

4.4.3 Nested Conditions + Nested Loops

អ្នកអាចបញ្ចូលគ្នា nested conditions និង nested loops។

#include <iostream>
using namespace std;

int main() {
    // បង្ហាញត្រីកោណមុំកែង
    int n;
    cout << "Enter size: ";
    cin >> n;
    
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            // nested condition
            if (j <= i) {
                cout << "* ";
            }
        }
        cout << endl;
    }
    
    return 0;
}

// ប្រសិនបើ n=5:
// *
// * *
// * * *
// * * * *
// * * * * *

លំហាត់ប្រចាំមេរៀនទី 4 - Control Structures

Exercise 1: សរសេរកម្មវិធីពិនិត្យមើលថាឆ្នាំមួយជា leap year ដែរឬទេ។ Leap year គឺឆ្នាំដែលចែកដោយ 4 បាន តែមិនចែកដោយ 100 បាន លើកលែងតែចែកដោយ 400 បាន។

Exercise 2: បង្កើត ATM menu program ដែលអនុញ្ញាតឱ្យអ្នកប្រើប្រាស់៖ 1)Check Balance, 2)Deposit, 3)Withdraw, 4)Exit។ ប្រើ do-while loop និង switch statement។

Exercise 3: សរសេរកម្មវិធីរកលេខ prime ទាំងអស់ពី 1 ដល់ 100។

Exercise 4: បង្កើតកម្មវិធីគណនា factorial នៃលេខមួយ (ឧទាហរណ៍ 5! = 5×4×3×2×1 = 120)។

Exercise 5: សរសេរកម្មវិធីបង្ហាញ pattern នេះដោយប្រើ nested loops៖
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

❖ 5. Functions in C++

5.1 Introduction to Functions រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition of Function (និយមន័យ)

Function គឺជា block នៃកូដដែលត្រូវបានរៀបចំឡើងដើម្បីធ្វើកិច្ចការជាក់លាក់មួយ។ Function អាចត្រូវបានហៅប្រើច្រើនដងក្នុងកម្មវិធី។

Function មានបួនផ្នែកសំខាន់ៗ៖

Why We Use Functions (ហេតុអ្វីប្រើ Functions)

1. Code Reusability (ការប្រើកូដឡើងវិញ)

សរសេរកូដតែម្តង ហើយប្រើវាច្រើនកន្លែង។

2. Code Organization (ការរៀបចំកូដ)

ធ្វើឱ្យកម្មវិធីមានរចនាសម្ព័ន្ធល្អ និងងាយស្រួលយល់។

3. Easy Maintenance (ងាយស្រួលថែរក្សា)

កែប្រែកូដនៅកន្លែងតែមួយ ប៉ះពាល់គ្រប់កន្លែងដែលប្រើ function នោះ។

4. Reduce Complexity (កាត់បន្ថយភាពស្មុគស្មាញ)

បែងចែកបញ្ហាធំជាបញ្ហាតូចៗ។

5. Team Collaboration (ការងារជាក្រុម)

អ្នកផ្សេងៗអាចសរសេរ functions ផ្សេងៗគ្នា។

Structure of a Function (រចនាសម្ព័ន្ធ Function)

returnType functionName(parameter1, parameter2, ...) {
    // Function body
    // Statements
    return value;  // (optional - អាស្រ័យលើ return type)
}

ឧទាហរណ៍:

int add(int a, int b) {
    int sum = a + b;
    return sum;
}

ពន្យល់៖

Function Prototype (ប្រកាសជាមុន)

Function prototype គឺជាការប្រកាស function មុនពេលកំណត់វា។ វាប្រាប់ compiler អំពី function signature។

Syntax:

returnType functionName(parameterTypes);

ឧទាហរណ៍:

#include <iostream>
using namespace std;

// Function Prototypes
int add(int, int);
void greet();
double calculateArea(double);

int main() {
    // ហៅ functions
    int result = add(5, 3);
    greet();
    double area = calculateArea(5.0);
    
    return 0;
}

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

void greet() {
    cout << "Hello!" << endl;
}

double calculateArea(double radius) {
    return 3.14159 * radius * radius;
}
សម្គាល់: Function prototype មិនចាំបាច់មានឈ្មោះ parameters ទេ គ្រាន់តែមាន types គ្រប់គ្រាន់ហើយ។ ប៉ុន្តែការដាក់ឈ្មោះធ្វើឱ្យកូដងាយយល់ជាង។

Function Call (ការហៅ Function)

ដើម្បីប្រើ function យើងត្រូវហៅវា (call it)។

#include <iostream>
using namespace std;

// Function definition
void displayMessage() {
    cout << "Welcome to C++ Programming!" << endl;
}
int main() {
    cout << "Start of program" << endl;
    // Function call
    displayMessage();
    displayMessage();  // អាចហៅច្រើនដង
    cout << "End of program" << endl;
    return 0;
}

// Output:
// Start of program
// Welcome to C++ Programming!
// Welcome to C++ Programming!
// End of program

5.2 Types of Functions រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

5.2.1 Built-in Functions (Library Functions)

Built-in functions គឺជា functions ដែល C++ ផ្តល់ឱ្យរួចស្រេចហើយ។ យើងគ្រាន់តែប្រើវាតាមរយៈ header files។

ឧទាហរណ៍ Built-in Functions:

Header File Functions Description
<iostream> cout, cin, endl Input/Output
<cmath> sqrt(), pow(), sin(), cos() Mathematical operations
<string> length(), substr(), find() String operations
<cctype> toupper(), tolower(), isdigit() Character operations
<ctime> time(), clock() Time operations
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main() {
    // Built-in functions from <cmath>
    double num = 16.0;
    cout << "sqrt(16) = " << sqrt(num) << endl;
    cout << "pow(2, 3) = " << pow(2, 3) << endl;
    // Built-in functions from <string>
    string text = "Hello";
    cout << "Length: " << text.length() << endl;
    return 0;
}

5.2.2 User-defined Functions

User-defined functions គឺជា functions ដែលយើងបង្កើតដោយខ្លួនឯងដើម្បីធ្វើកិច្ចការជាក់លាក់។

#include <iostream>
using namespace std;

// User-defined function
int findMax(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

// User-defined function
bool isEven(int num) {
    return (num % 2 == 0);
}

int main() {
    int x = 10, y = 25;
    
    cout << "Maximum: " << findMax(x, y) << endl;
    cout << "Is 10 even? " << isEven(10) << endl;
    
    return 0;
}

5.3 Parameters and Return Types រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

5.3.1 No Parameter and No Return Type

Function មិនទទួល input និងមិន return output។

#include <iostream>
using namespace std;

void displayWelcome() {
    cout << "========================================" << endl;
    cout << "  Welcome to Student Management System  " << endl;
    cout << "========================================" << endl;
}

int main() {
    displayWelcome();
    
    // កូដផ្សេងទៀត...
    
    return 0;
}

5.3.2 With Parameter and No Return Type

Function ទទួល input តែមិន return output។

#include <iostream>
using namespace std;

void displaySquare(int num) {
    int square = num * num;
    cout << "Square of " << num << " is " << square << endl;
}

void user(string name) {
    cout << "Hello, " << name << "!" << endl;
    cout << "Welcome to our program!" << endl;
}

int main() {
    displaySquare(5);
    displaySquare(10);
    
    user("Sokha");
    user("Dara");
    
    return 0;
}

5.3.3 No Parameter and With Return Type

Function មិនទទួល input តែ return output។

#include <iostream>
using namespace std;

int RandomNumber() {
    // សម្រាប់ឧទាហរណ៍ យើង return fixed value
    return 42;
}

double Pi() {
    return 3.14159;
}

string Day() {
    return "Monday";
}

int main() {
    int num = RandomNumber();
    double pi = Pi();
    string day = Day();
    
    cout << "Random number: " << num << endl;
    cout << "Pi value: " << pi << endl;
    cout << "Today is: " << day << endl;
    
    return 0;
}

5.3.4 With Parameter and With Return Type

Function ទាំងទទួល input និង return output។ នេះជាប្រភេទ function ដែលប្រើច្រើនបំផុត។

#include <iostream>
#include <cmath>
using namespace std;

// ផលបូក
int add(int a, int b) {
    return a + b;
}

// ផលគុណ
double multiply(double x, double y) {
    return x * y;
}

// គណនាផ្ទៃត្រីកោណ
double triangleArea(double base, double height) {
    return 0.5 * base * height;
}

int main() {
    cout << "5 + 3 = " << add(5, 3) << endl;
    cout << "2.5 * 4 = " << multiply(2.5, 4) << endl;
    cout << "Triangle area: " << triangleArea(10, 5) << endl;    
    return 0;
}

5.3.5 Pass by Value

នៅពេល pass by value, function ទទួលច្បាប់ចម្លងនៃតម្លៃ។ ការផ្លាស់ប្តូរ parameter ក្នុង function មិនប៉ះពាល់ដល់ original variable។

#include <iostream>
using namespace std;

void modifyValue(int x) {
    x = x * 2;
    cout << "Inside function: x = " << x << endl;
}

int main() {
    int num = 10;
    
    cout << "Before function call: num = " << num << endl;

    modifyValue(num); // x = x * 2

    cout << "After function call: num = " << num << endl;

    return 0;
}

// Output:
// Before function call: num = 10
// Inside function: x = 20
// After function call: num = 10  (មិនផ្លាស់ប្តូរ!)

5.3.6 Pass by Reference

នៅពេល pass by reference (ប្រើ &), function ធ្វើការលើ original variable។ ការផ្លាស់ប្តូរប៉ះពាល់ដល់ original variable។

#include <iostream>
using namespace std;

void modifyValue(int &x) {  // សម្គាល់ & symbol
    x = x * 2;
    cout << "Inside function: x = " << x << endl;
}
int main() {
    int num = 10;
    cout << "Before function call: num = " << num << endl;
    modifyValue(num);
    cout << "After function call: num = " << num << endl;
    return 0;
}

// Output:
// Before function call: num = 10
// Inside function: x = 20
// After function call: num = 20  (ផ្លាស់ប្តូរ!)
ពេលណាប្រើ Pass by Value vs Pass by Reference:
  • Pass by Value: ប្រើនៅពេលមិនចង់ផ្លាស់ប្តូរ original variable
  • Pass by Reference: ប្រើនៅពេលចង់ផ្លាស់ប្តូរ original variable ឬចង់ជៀសវាង copying data ធំៗ

5.3.7 Default Arguments

Default arguments អនុញ្ញាតឱ្យ parameters មានតម្លៃ default។ ប្រសិនបើមិនផ្តល់តម្លៃ នឹងប្រើតម្លៃ default។

#include <iostream>
using namespace std;

// Function ជាមួយ default arguments
void displayInfo(string name, int age = 18, string city = "Phnom Penh") {
    cout << "Name: " << name << endl;
    cout << "Age: " << age << endl;
    cout << "City: " << city << endl;
    cout << "-------------------" << endl;
}
int main() {
    displayInfo("Sokha");                      // ប្រើ default age និង city
    displayInfo("Dara", 25);                   // ប្រើ default city តែប៉ុណ្ណោះ
    displayInfo("Bopha", 22, "Siem Reap");    // ផ្តល់តម្លៃទាំងអស់
    return 0;
}

// Output:
// Name: Sokha
// Age: 18
// City: Phnom Penh
// -------------------
// Name: Dara
// Age: 25
// City: Phnom Penh
// -------------------
// Name: Bopha
// Age: 22
// City: Siem Reap
// -------------------
ច្បាប់សម្រាប់ Default Arguments:
  • Default arguments ត្រូវតែនៅខាងស្តាំនៃ parameter list
  • មិនអាចមាន non-default parameter បន្ទាប់ពី default parameter
  • Default values ត្រូវកំណត់ក្នុង function prototype ឬ definition (មិនមែនទាំងពីរ)
// ត្រឹមត្រូវ
void func1(int a, int b = 5, int c = 10); // [No] [Default] [Default]
void func2(int a, string b = "Hello"); // [No] [Default]
void func3(int a = 10, string b = "Hello"); // [Default] [Default]

// មិនត្រឹមត្រូវ
void func4(int a = 5, int b);             // ERROR!: [Default] [No]
void func5(int a = 5, int b, int c = 10); // ERROR!: [Default] [No] [Default]

5.4 Function Overloading រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Function Overloading គឺជាលក្ខណៈពិសេសដែលអនុញ្ញាតឱ្យមាន functions ច្រើនដែលមានឈ្មោះដូចគ្នា តែ parameters ខុសគ្នា។

លក្ខខណ្ឌសម្រាប់ Function Overloading:

សំខាន់: Function overloading មិនមើល return type ទេ។ មើលតែ parameters!

ឧទាហរណ៍:

#include <iostream>
using namespace std;

// Function overloading - ចំនួន parameters ខុសគ្នា
int add(int a, int b) {
    return a + b;
}
int add(int a, int b, int c) {
    return a + b + c;
}
// Function overloading - ប្រភេទ parameters ខុសគ្នា
double add(double a, double b) {
    return a + b;
}
int main() {
    cout << "add(5, 4) = " << add(5, 4) << endl;
    cout << "add(5, 4, 3) = " << add(5, 4, 3) << endl;
    cout << "add(5.5, 4.4) = " << add(5.5, 4.4) << endl;
    return 0;
}
// Output:
// add(5, 4) = 9
// add(5, 4, 3) = 12
// add(5.5, 4.4) = 9.9

ឧទាហរណ៍ពេញលេញ - ផ្ទៃនៃទម្រង់ផ្សេងៗ:

#include <iostream>
#include <cmath>
using namespace std;

// គណនាផ្ទៃចតុកោណកែង
double area(double length, double width) {
    return length * width;
}

// គណនាផ្ទៃការ៉េ
double area(double side) {
    return side * side;
}

// គណនាផ្ទៃរង្វង់
double areaCircle(double radius) {
    return 3.14159 * radius * radius;
}

int main() {
    cout << "===== Area Calculator =====" << endl;
    cout << "Rectangle (5 x 3): " << area(5.0, 3.0) << endl;
    cout << "Square (4 x 4): " << area(4.0) << endl;
    cout << "Circle (radius=5): " << areaCircle(5.0) << endl;
    return 0;
}

លំហាត់ប្រចាំមេរៀនទី 5 - Functions

Exercise 1: សរសេរ function factorial() ដែលគណនា factorial នៃលេខមួយ។ ឧទាហរណ៍ factorial(5) = 5 × 4 × 3 × 2 × 1 = 120

Exercise 2: បង្កើត function isPalindrome() ដែលពិនិត្យមើលថាលេខមួយជា palindrome ដែរឬទេ។ Palindrome គឺលេខដែលអានពីឆ្វេងទៅស្តាំ និងស្តាំទៅឆ្វេងដូចគ្នា (ឧទាហរណ៍ 121, 12321)។

Exercise 3: សរសេរ overloaded functions power() ដែល៖
- power(int base, int exp) - គណនា base^exp
- power(double base) - គណនា base^2 (square)
- power(double base, double exp) - គណនា base^exp ជាមួយ floating-point

Exercise 4: បង្កើត function calculateBMI() ដែលគណនា Body Mass Index។ Function នេះគួរតែមាន 2 versions:
- calculateBMI(double weight, double height) - គណនា BMI
- calculateBMI(double weight, double height, string &result) - គណនា BMI និងផ្តល់ result string (Underweight, Normal, Overweight, Obese) តាមរយៈ reference parameter

Exercise 5: សរសេរកម្មវិធី Calculator ពេញលេញដែលប្រើ functions សម្រាប់ operations ផ្សេងៗ (add, subtract, multiply, divide, power, sqrt)។ Program គួរតែមាន menu និងអនុញ្ញាតឱ្យអ្នកប្រើប្រាស់ធ្វើ calculations ច្រើនដងរហូតដល់ជ្រើសរើស exit។

❖ 6. Arrays in C++

6.1 Introduction to Array រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Array គឺជា collection នៃ elements ដែលមានប្រភេទដូចគ្នា រក្សាទុកក្នុង memory locations ជាប់គ្នា។ Array អនុញ្ញាតឱ្យយើងរក្សាទុកតម្លៃច្រើនក្នុង variable តែមួយ។

ពេលណាប្រើ Arrays:

គុណសម្បត្តិនៃ Arrays:

6.2 Array Declaration រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Syntax:

dataType arrayName[arraySize];

ឧទាហរណ៍:

int numbers[5];        // Array របស់ 5 integers
double prices[10];     // Array របស់ 10 doubles
char letters[26];      // Array របស់ 26 characters
string names[100];     // Array របស់ 100 strings
សំខាន់:
  • Array size ត្រូវតែជា constant value (មិនអាចប្រើ variable)
  • Array indexing ចាប់ផ្តើមពី 0
  • Array size ត្រូវកំណត់នៅពេល compile time

6.3 Array Indexing រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

នៅក្នុង C++, array indexing ចាប់ផ្តើមពី 0។ មានន័យថា:

#include <iostream>
using namespace std;

int main() {
    int numbers[5];
    
    // ផ្តល់តម្លៃដល់ array elements
    numbers[0] = 10;
    numbers[1] = 20;
    numbers[2] = 30;
    numbers[3] = 40;
    numbers[4] = 50;
    
    // Access និងបង្ហាញ array elements
    cout << "First element: " << numbers[0] << endl;
    cout << "Second element: " << numbers[1] << endl;
    cout << "Last element: " << numbers[4] << endl;
    
    // កែប្រែតម្លៃ
    numbers[2] = 35;
    cout << "Modified third element: " << numbers[2] << endl;
    
    return 0;
}
Array Bounds: C++ មិនពិនិត្យ array bounds ទេ! ការ access index ដែលមិនត្រឹមត្រូវ (ដូចជា numbers[10] សម្រាប់ array size 5) នឹងបណ្តាលឱ្យមាន undefined behavior និង bugs ធ្ងន់ធ្ងរ។

6.4 Array with Loop រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Arrays និង loops ធ្វើការល្អជាមួយគ្នា។ យើងប្រើ loops ដើម្បីដំណើរការ array elements។

បញ្ចូលទិន្នន័យទៅក្នុង Array:

#include <iostream>
using namespace std;

int main() {
    const int SIZE = 5;
    int numbers[SIZE];
    
    // បញ្ចូលទិន្នន័យ
    cout << "Enter " << SIZE << " numbers:" << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << "Number " << (i+1) << ": ";
        cin >> numbers[i];
    }
    
    // បង្ហាញទិន្នន័យ
    cout << "\nYou entered:" << endl;
    for (int i = 0; i < SIZE; i++) {
        cout << numbers[i] << " ";
    }
    cout << endl;
    
    return 0;
}

គណនាផលបូកនៃ Array Elements:

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    int size = 5;
    int sum = 0;
    
    // គណនាផលបូក
    for (int i = 0; i < size; i++) {
        sum += numbers[i];
    }
    
    cout << "Sum = " << sum << endl;
    cout << "Average = " << (double)sum / size << endl;
    return 0;
}

6.5 Array Initialization រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

មានវិធីច្រើនដើម្បី initialize arrays:

1. Initialize នៅពេល Declaration:

int numbers[5] = {10, 20, 30, 40, 50};
double prices[3] = {19.99, 25.50, 30.00};
char grades[4] = {'A', 'B', 'C', 'D'};

2. Partial Initialization:

int numbers[5] = {10, 20};  // នៃសល់គឺ 0
// numbers = {10, 20, 0, 0, 0}

3. Initialize ទាំងអស់ជា 0:

int numbers[5] = {0};  // ទាំងអស់គឺ 0
// numbers = {0, 0, 0, 0, 0}

4. Initialize ដោយគ្មាន Size:

int numbers[] = {10, 20, 30, 40, 50};  // Size = 5 (កំណត់ដោយស្វ័យប្រវត្តិ)

ឧទាហរណ៍ពេញលេញ:

#include <iostream>
using namespace std;

int main() {
    // វិធីផ្សេងៗនៃ initialization
    int arr1[5] = {1, 2, 3, 4, 5};
    int arr2[5] = {10, 20};           // {10, 20, 0, 0, 0}
    int arr3[5] = {0};                // {0, 0, 0, 0, 0}
    int arr4[] = {100, 200, 300};     // Size = 3
    
    // បង្ហាញ arr2
    cout << "arr2: ";
    for (int i = 0; i < 5; i++) {
        cout << arr2[i] << " ";
    }
    cout << endl;
    
    // បង្ហាញ arr4
    cout << "arr4: ";
    for (int i = 0; i < 3; i++) {
        cout << arr4[i] << " ";
    }
    cout << endl;
    
    return 0;
}

រកទំហំ Array (Array Size):

#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};
    
    // គណនា size របស់ array
    int size = sizeof(numbers) / sizeof(numbers[0]);
    
    cout << "Array size: " << size << endl;
    
    return 0;
}

លំហាត់ប្រចាំមេរៀនទី 6 - Arrays

Exercise 1: សរសេរកម្មវិធីដែលរក second largest number ក្នុង array។

Exercise 2: បង្កើតកម្មវិធីដែល reverse array (បញ្ច្រាស់លំដាប់ elements)។ ឧទាហរណ៍ {1, 2, 3, 4, 5} → {5, 4, 3, 2, 1}

Exercise 3: សរសេរកម្មវិធីដែលរកលេខដែលកើតមានច្រើនបំផុតក្នុង array (mode)។

Exercise 4: បង្កើត program ដែល merge two sorted arrays ទៅជា one sorted array។

Exercise 5: សរសេរកម្មវិធី C++ ដែលធ្វើការ initialize array តាមវិធីផ្សេងៗគ្នា រួចបង្ហាញលទ្ធផល។

❖ 7. Pointers in C++

7.1 Introduction to Pointers រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Pointer គឺជា variable ដែលរក្សាទុក memory address របស់ variable មួយទៀត។ ជាជាងរក្សាទុកតម្លៃដោយផ្ទាល់ pointer រក្សាទុកទីតាំងក្នុង memory ដែលតម្លៃនោះស្ថិតនៅ។

ហេតុអ្វីប្រើ Pointers:

ការយល់ដឹងមូលដ្ឋាន:
សម្មតិថាយើងមាន variable int x = 10;
- x គឺជា variable ដែលរក្សាទុកតម្លៃ 10
- Variable នេះមានទីតាំងក្នុង memory (ឧទាហរណ៍ address 0x1000)
- Pointer អាចរក្សាទុក address នេះ (0x1000)

Pointer Declaration

Syntax:

dataType *pointerName;

ឧទាហរណ៍:

int *ptr;        // Pointer to integer
double *dptr;    // Pointer to double
char *cptr;      // Pointer to character
string *sptr;    // Pointer to string
សំខាន់: * symbol សម្គាល់ថានេះជា pointer variable។ ប៉ុន្តែកុំច្រឡំជាមួយ dereference operator ដែលយើងនឹងសិក្សានៅខាងក្រោម។

Address Operator (&)

& operator ប្រើដើម្បីទទួល memory address របស់ variable។

#include <iostream>
using namespace std;
int main() {
    int num = 42;
    cout << "Value of num: " << num << endl;
    cout << "Address of num: " << &num << endl;  
    return 0;
}

Assigning Address to Pointer:

#include <iostream>
using namespace std;

int main() {
    int num = 42;
    int *ptr;  // ប្រកាស pointer
    
    ptr = &num;  // ផ្តល់ address របស់ num ទៅ ptr
    
    cout << "Value of num: " << num << endl;
    cout << "Address of num: " << &num << endl;
    cout << "Value of ptr (address it points to): " << ptr << endl;
    cout << "Address of ptr itself: " << &ptr << endl;
    
    return 0;
}

Dereference Operator (*)

* operator (នៅពេលប្រើជាមួយ pointer variable) ប្រើដើម្បី access តម្លៃនៅ address ដែល pointer កំណត់។ នេះហៅថា "dereferencing"។

#include <iostream>
using namespace std;

int main() {
    int num = 42;
    int *ptr = &num;
    
    cout << "Value of num: " << num << endl;
    cout << "Value through pointer (*ptr): " << *ptr << endl;
    
    // កែប្រែតម្លៃតាមរយៈ pointer
    *ptr = 100;
    
    cout << "\nAfter changing value through pointer:" << endl;
    cout << "Value of num: " << num << endl;
    cout << "Value through pointer (*ptr): " << *ptr << endl;
    
    return 0;
}

// Output:
// Value of num: 42
// Value through pointer (*ptr): 42
//
// After changing value through pointer:
// Value of num: 100
// Value through pointer (*ptr): 100

សង្ខេប Pointer Operators:

Operator Name Description Example
& Address-of ទទួល address របស់ variable ptr = &num;
* Dereference Access តម្លៃនៅ address value = *ptr;
* Declaration ប្រកាស pointer variable int *ptr;

ឧទាហរណ៍ពេញលេញ - Pointers Basics:

#include <iostream>
using namespace std;

int main() {
    // ប្រកាស និង initialize variables
    int a = 10;
    int b = 20;
    
    // ប្រកាស pointers
    int *ptr1 = &a;
    int *ptr2 = &b;
    
    cout << "===== Initial Values =====" << endl;
    cout << "a = " << a << ", address: " << &a << endl;
    cout << "b = " << b << ", address: " << &b << endl;
    cout << "*ptr1 = " << *ptr1 << ", ptr1 points to: " << ptr1 << endl;
    cout << "*ptr2 = " << *ptr2 << ", ptr2 points to: " << ptr2 << endl;
    
    // កែប្រែតាមរយៈ pointers
    *ptr1 = 100;
    *ptr2 = 200;
    
    cout << "\n===== After Modification =====" << endl;
    cout << "a = " << a << endl;
    cout << "b = " << b << endl;
    
    return 0;
}

7.2 Pointer to Pointers រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition

Pointer to pointer គឺជា pointer ដែលរក្សាទុក address របស់ pointer មួយទៀត។

Syntax: dataType **pointerName;
#include <iostream>
using namespace std;
int main() {
    int num = 42;
    int *ptr = &num;       // Pointer to int
    int **pptr = &ptr;     // Pointer to pointer to int
    
    cout << "Value of num: " << num << endl;
    cout << "Address of num: " << &num << endl;
    cout << endl;
    cout << "Value of ptr (address of num): " << ptr << endl;
    cout << "Value through ptr (*ptr): " << *ptr << endl;
    cout << "Address of ptr: " << &ptr << endl;
    cout << endl;
    cout << "Value of pptr (address of ptr): " << pptr << endl;
    cout << "Value through pptr (*pptr = address of num): " << *pptr << endl;
    cout << "Value through pptr (**pptr = value of num): " << **pptr << endl;
    
    **pptr = 100; // កែប្រែតម្លៃតាមរយៈ pointer to pointer
    cout << "\nAfter **pptr = 100:" << endl;
    cout << "num = " << num << endl;
    return 0;
}

7.3 Pointer to Function រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition

Function pointers រក្សាទុក address របស់ functions។ ពួកវាអនុញ្ញាតឱ្យយើងផ្ទេរ functions ជា arguments ឬរក្សាទុក functions ក្នុង arrays។

Syntax:

returnType (*pointerName)(parameterTypes);

ឧទាហរណ៍:

#include <iostream>
using namespace std;
// Functions
int add(int a, int b) {
    return a + b;
}
int subtract(int a, int b) {
    return a - b;
}
int main() {
    // ប្រកាស function pointer
    int (*operation)(int, int); 
    // ផ្តល់ address របស់ function
    operation = add;
    cout << "10 + 5 = " << operation(10, 5) << endl; 
    operation = subtract;
    cout << "10 - 5 = " << operation(10, 5) << endl;
    return 0;
}

លំហាត់ប្រចាំមេរៀនទី 7 - Pointers

Exercise 1: សរសេរ function void printValue(int *ptr) ដែលទទួលយក pointer មួយ រួចបង្ហាញតម្លៃដែល pointer នោះចង្អុលទៅ។ នៅក្នុង main() បង្កើតអថេរ int num = 99; រួចហៅ function ដោយបញ្ជួន address
របស់ num

Exercise 2: សរសេរកម្មវិធីដែលបង្កើត array int arr[8] = {10, 20, 30, 40, 50, 60, 70, 80}; ប្រើ Pointer Arithmetic (មិនប្រើ index []) ដើម្បីបង្ហាញធាតុទាំងអស់នៃ array ពីមុខទៅក្រោយ និងពីក្រោយមកមុខ។

Exercise 3: បង្កើតមុខងារ ៣ ខាងក្រោម៖ int square(int x), int cube(int x), int absolute(int x) បង្កើត Array of Function Pointers ឈ្មោះ int (*operations[3])(int); នៅក្នុង main() តាំងមុខងារទាំង ៣ ទៅក្នុង array នោះ រួចប្រើ loop ដើម្បីគណនា និងបង្ហាញលទ្ធផលសម្រាប់លេខ x = 7។

Exercise 4: បង្កើត program ដែលប្រើ array of function pointers ដើម្បីធ្វើ calculator menu (add, subtract, multiply, divide)។

Exercise 5: Menu using Array of Function Pointers បង្កើត Calculator Menu ដោយប្រើ Array of Function Pointers។ តម្រូវការ៖
- បង្កើតមុខងារ ៤ ដូចខាងក្រោម៖ add, subtract, multiply, divide (ប្រភេទ double)
- បង្កើត array of function pointers
- បង្ហាញម៉ឺនុយ (1. Add, 2. Subtract, 3. Multiply, 4. Divide, 5. Exit)
- អនុញ្ញាតឱ្យអ្នកប្រើជ្រើសរើសលេខ រួចគណនាតាមជម្រើសនោះដោយប្រើ function pointer។
- អាចប្រើ loop រហូតដល់អ្នកប្រើជ្រើសរើស Exit។

❖ 8. OOP in C++ (Object-Oriented Programming in C++)

8.1 Introduction to OOP រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

What is OOP?

Object-Oriented Programming (OOP) គឺជា programming paradigm ដែលផ្អែកលើគំនិតនៃ "objects" ដែលមាន data (attributes) និង code (methods)។ OOP រៀបចំកម្មវិធីជុំវិញ objects ជាជាង functions និង logic។

គំនិតសំខាន់ៗ:

Why use OOP? (ហេតុអ្វីប្រើ OOP)

1. Modularity (លក្ខណៈម៉ូឌុល)

កូដត្រូវបានបែងចែកជា classes ដែលឯករាជ្យ ធ្វើឱ្យងាយស្រួលថែរក្សា។

2. Reusability (ការប្រើឡើងវិញ)

Classes អាចប្រើឡើងវិញនៅកន្លែងផ្សេងៗក្នុងកម្មវិធី ឬក្នុងគម្រោងផ្សេងទៀត។

3. Data Hiding (ការលាក់ទិន្នន័យ)

ទិន្នន័យសម្ងាត់អាចត្រូវបានលាក់ពីផ្នែកខាងក្រៅ (encapsulation)។

4. Easy Maintenance (ងាយស្រួលថែរក្សា)

កែប្រែ class មួយមិនប៉ះពាល់ដល់កូដផ្សេងទៀត។

5. Real-world Modeling (ការតាក់តែងពិភពពិត)

OOP ធ្វើឱ្យងាយស្រួលក្នុងការតំណាង real-world entities ក្នុងកូដ។

Class and Object

Class Definition:

Class គឺជា blueprint ឬ template សម្រាប់បង្កើត objects។ វាកំណត់ properties និង behaviors ដែល objects នឹងមាន។

Object Definition:

Object គឺជា instance នៃ class។ វាជា concrete entity ដែលបង្កើតពី class blueprint។

ឧទាហរណ៍ពិភពពិត:
Class: Car (ការរចនាទូទៅនៃឡាន)
Objects:
- Toyota Camry របស់ខ្ញុំ (ពណ៌ខ្មៅ, ឆ្នាំ 2020)
- Honda Civic របស់អ្នក (ពណ៌ស, ឆ្នាំ 2021)
- Ford Mustang របស់គេ (ពណ៌ក្រហម, ឆ្នាំ 2022)

Syntax របស់ Class:

class ClassName {
    // Access specifier
    private:
        // Private members
    
    public:
        // Public members
        // Constructor
        // Methods
};

ឧទាហរណ៍សាមញ្ញ:

#include <iostream>
#include <string>
using namespace std;

// កំណត់ Class
class Student {
public:
    // Data Members (Attributes)
    string name;
    int age;
    double gpa;
    
    // Member Function (Method)
    void displayInfo() {
        cout << "Name: " << name << endl;
        cout << "Age: " << age << endl;
        cout << "GPA: " << gpa << endl;
    }
};

int main() {
    // បង្កើត Objects (Instances)
    Student student1;
    Student student2;
    
    // ផ្តល់តម្លៃទៅ object1
    student1.name = "Sokha";
    student1.age = 20;
    student1.gpa = 3.75;
    
    // ផ្តល់តម្លៃទៅ object2
    student2.name = "Dara";
    student2.age = 21;
    student2.gpa = 3.90;
    
    // ហៅ methods
    cout << "Student 1:" << endl;
    student1.displayInfo();
    
    cout << "\nStudent 2:" << endl;
    student2.displayInfo();
    
    return 0;
}

Data Members & Member Functions

Data Members (Attributes/Properties):

Variables ដែលកំណត់ក្នុង class ហៅថា data members។ ពួកវារក្សាទុក state របស់ object។

Member Functions (Methods):

Functions ដែលកំណត់ក្នុង class ហៅថា member functions។ ពួកវាកំណត់ behavior របស់ object។

class Rectangle {
public:
    // Data Members
    double length;
    double width;
    
    // Member Functions
    double calculateArea() {
        return length * width;
    }  
    double calculatePerimeter() {
        return 2 * (length + width);
    }
    
    void display() {
        cout << "Length: " << length << endl;
        cout << "Width: " << width << endl;
        cout << "Area: " << calculateArea() << endl;
        cout << "Perimeter: " << calculatePerimeter() << endl;
    }
};

Access Specifiers (កម្រិតការចូលប្រើ)

Access specifiers កំណត់ថា members របស់ class អាចចូលប្រើបានពីណា។ C++ មាន 3 access specifiers:

Specifier Description Access
public អាចចូលប្រើពីគ្រប់កន្លែង Class, Derived Classes, Outside
private អាចចូលប្រើតែក្នុង class តែប៉ុណ្ណោះ Class only
protected អាចចូលប្រើក្នុង class និង derived classes Class and Derived Classes
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
private:
    // Private members - មិនអាចចូលប្រើពីខាងក្រៅ
    double balance;
    string accountNumber;
public:
    // Public members - អាចចូលប្រើពីខាងក្រៅ
    string ownerName;
    // Public methods ដើម្បី access private data
    void setBalance(double amount) {
        if (amount >= 0) {
            balance = amount;
        }
    }
    double getBalance() {
        return balance;
    }


    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            cout << "Deposited: $" << amount << endl;
        }
    }
    void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            cout << "Withdrawn: $" << amount << endl;
        } else {
            cout << "Insufficient funds!" << endl;
        }
    }
};

int main() {
    BankAccount account;
    account.ownerName = "Sokha";
    account.setBalance(1000.0);
    
    cout << "Owner: " << account.ownerName << endl;
    cout << "Balance: $" << account.getBalance() << endl;
    
    account.deposit(500);
    account.withdraw(200);
    cout << "Final Balance: $" << account.getBalance() << endl;
    
    // account.balance = 5000;  // ERROR - balance is private!
    return 0;
}

Constructors (អ្នកសាងសង់)

Definition:

Constructor គឺជា special member function ដែលត្រូវបានហៅដោយស្វ័យប្រវត្តិនៅពេលបង្កើត object។ វាប្រើដើម្បី initialize object។

លក្ខណៈពិសេសនៃ Constructor:

ប្រភេទ Constructors:

1. Default Constructor (គ្មាន parameters):

class Student {
public:
    string name;
    int age;
    
    // Default Constructor
    Student() {
        name = "Unknown";
        age = 0;
        cout << "Default constructor called!" << endl;
    }
};

2. Parameterized Constructor:

class Student {
public:
    string name;
    int age;
    
    // Parameterized Constructor
    Student(string n, int a) {
        name = n;
        age = a;
        cout << "Parameterized constructor called!" << endl;
    }
};

3. Copy Constructor:

class Student {
public:
    string name;
    int age;
    
    // Copy Constructor
    Student(const Student &other) {
        name = other.name;
        age = other.age;
        cout << "Copy constructor called!" << endl;
    }
};

ឧទាហរណ៍ពេញលេញ:

#include <iostream>
#include <string>
using namespace std;

class Car {
private:
    string brand;
    string model;
    int year;
    double price;
public:
    // Default Constructor
    Car() {
        brand = "Unknown";
        model = "Unknown";
        year = 2000;
        price = 0.0;
    }
    // Parameterized Constructor
    Car(string b, string m, int y, double p) {
        brand = b;
        model = m;
        year = y;
        price = p;
    }
    // Constructor with some default parameters
    Car(string b, string m) {
        brand = b;
        model = m;
        year = 2024;
        price = 0.0;
    }
    


    // Copy Constructor
    Car(const Car &other) {
        brand = other.brand;
        model = other.model;
        year = other.year;
        price = other.price;
        cout << "Car copied!" << endl;
    }
    
    void displayInfo() {
        cout << "Brand: " << brand << endl;
        cout << "Model: " << model << endl;
        cout << "Year: " << year << endl;
        cout << "Price: $" << price << endl;
        cout << "-------------------" << endl;
    }
};

int main() {
    // ប្រើ default constructor
    Car car1;
    cout << "Car 1:" << endl;
    car1.displayInfo();
    
    // ប្រើ parameterized constructor
    Car car2("Toyota", "Camry", 2023, 35000);
    cout << "Car 2:" << endl;
    car2.displayInfo();
    
    // ប្រើ constructor ជាមួយ partial parameters
    Car car3("Honda", "Civic");
    cout << "Car 3:" << endl;
    car3.displayInfo();
    
    // ប្រើ copy constructor
    Car car4 = car2;
    cout << "Car 4 (copy of car2):" << endl;
    car4.displayInfo();
    return 0;
}

Destructors (អ្នកបំផ្លាញ)

Definition:

Destructor គឺជា special member function ដែលត្រូវបានហៅដោយស្វ័យប្រវត្តិនៅពេល object ត្រូវបាន destroyed។ វាប្រើដើម្បីសម្អាត resources (memory, files, etc)។

លក្ខណៈពិសេសនៃ Destructor:

#include <iostream>
using namespace std;

class Demo {
public:
    Demo() {
        cout << "Object created" << endl;
    }


    ~Demo() {  // Destructor
        cout << "Object destroyed" << endl;
    }
};

int main() {
    cout << "Start main" << endl;
    Demo obj;  // Constructor ត្រូវបានហៅ
    cout << "End main" << endl;
    return 0;  // Destructor ត្រូវបានហៅនៅទីនេះ
}

// Output:
// Start main
// Object created
// End main
// Object destroyed

this Pointer

Definition:this គឺជា pointer ពិសេសដែលកំណត់ទៅកាន់ object បច្ចុប្បន្ន។ វាអាចប្រើក្នុង member functions ដើម្បី access members របស់ object ដែលហៅ function។

ការប្រើប្រាស់ this:

#include <iostream>
#include <string>
using namespace std;

class Person {
private:
    string name;
    int age;
public:
    // Constructor ប្រើ this ដើម្បីបញ្ជាក់ member variables
    Person(string name, int age) {
        this->name = name;  // this->name គឺ member variable
        this->age = age;    // name គឺ parameter
    }
    // Method ដែល return reference ទៅ object បច្ចុប្បន្ន
    Person& setName(string name) {
        this->name = name;
        return *this;  // return object បច្ចុប្បន្ន
    }
    Person& setAge(int age) {
        this->age = age;
        return *this;
    }
    void display() {
        cout << "Name: " << this->name << endl;
        cout << "Age: " << this->age << endl;
    }
};
int main() {
    Person person("Sokha", 20);
    // Method chaining (អាចធ្វើបានដោយសារ return *this)
    person.setName("Dara").setAge(25);
    person.display();
    return 0;
}

8.2 Core OOP Concepts រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

OOP មាន 4 principles (pillars) សំខាន់ៗ៖

8.2.1 Encapsulation (ការរុំបញ្ចូល) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

What is Encapsulation?

Encapsulation គឺជាការរុំបញ្ចូល data (variables) និង code (methods) ដែលដំណើរការលើ data នោះក្នុង unit តែមួយ (class)។ វារួមបញ្ចូលទាំងការលាក់ data ពីការចូលប្រើដោយផ្ទាល់ពីខាងក្រៅ។

Why use Encapsulation?

Syntax of Encapsulation:

class ClassName {
private:
    // Private data members
    dataType variable1;
    dataType variable2;

public:
    // Public methods to access private data
    void setVariable1(dataType value) {
        // Validation
        variable1 = value;
    }
    
    dataType getVariable1() {
        return variable1;
    }
};

Example - Bank Account with Encapsulation:

#include <iostream>
#include <string>
using namespace std;

class BankAccount {
private:
    double balance;  // private variable

public:
    // setter
    void setBalance(double b) {
        if(b >= 0)  // validate balance
            balance = b;
        else
            cout << "Invalid balance!" << endl;
    }

    // getter
    double getBalance() {
        return balance;
    }
};

int main() {
    BankAccount account;

    account.setBalance(1000.50);  // set balance
    cout << "Balance: $" << account.getBalance() << endl;

    account.setBalance(-500);     // try invalid
    cout << "Balance after invalid set: $" << account.getBalance() << endl;

    return 0;
}

// Balance: $1000.5
// Invalid balance!
// Balance after invalid set: $1000.5

8.2.2 Inheritance (ការទទួលមរតក) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

What is Inheritance?

Inheritance គឺជាយន្តការដែលអនុញ្ញាតឱ្យ class មួយ (derived/child class) ទទួលបាន properties និង methods ពី class មួយទៀត (base/parent class)។

Why use Inheritance?

Syntax of Inheritance:

class BaseClass {
    // Base class members
};

class DerivedClass : accessSpecifier BaseClass {
    // Derived class members
    // + inherited members from BaseClass
};

Access Specifiers ក្នុង Inheritance:

Inheritance Type public members protected members private members
public public protected not accessible
protected protected protected not accessible
private private private not accessible

Example - Simple Inheritance:

#include <iostream>
#include <string>
using namespace std;

// Base Class
class Animal {
protected:
    string name;
    int age;
public:
    // Constructor
    Animal(string n, int a) {
        name = n;
        age = a;
    }
    // Method to eat
    void eat() {
        cout << name << " is eating." << endl;
    }
    // Method to sleep
    void sleep() {
        cout << name << " is sleeping." << endl;
    }
    // Display info
    void displayInfo() {
        cout << "Name: " << name << ", Age: " << age << endl;
    }
};

// Derived Class Dog
class Dog : public Animal {
public:
    // Constructor uses Base class constructor
    Dog(string n, int a) : Animal(n, a) {}

    void bark() {
        cout << name << " says: Woof! Woof!" << endl;
    }
};




// Derived Class Cat
class Cat : public Animal {
public:
    Cat(string n, int a) : Animal(n, a) {}

    void meow() {
        cout << name << " says: Meow! Meow!" << endl;
    }
};

int main() {
    Dog dog1("Dingi", 3);
    Cat cat1("Momo", 2);

    cout << "===== Dog =====" << endl;
    dog1.displayInfo();  // inherited
    dog1.eat();          // inherited
    dog1.bark();         // own method

    cout << "===== Cat =====" << endl;
    cat1.displayInfo();  // inherited
    cat1.sleep();        // inherited
    cat1.meow();         // own method

    return 0;
}

// Output:
// ===== Dog =====
// Name: Dingi, Age: 3
// Dingi is eating.
// Dingi says: Woof! Woof!
// ===== Cat =====
// Name: Momo, Age: 2
// Momo is sleeping.
// Momo says: Meow! Meow!

8.2.3 Polymorphism (ពហុរូបភាព) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

What is Polymorphism?

Polymorphism មកពីពាក្យ Greek ដែលមានន័យថា "many forms"។ វាអនុញ្ញាតឱ្យ objects ខុសៗគ្នាឆ្លើយតបទៅនឹង message ដូចគ្នាតាមរបៀបផ្សេងៗគ្នា។

ប្រភេទ Polymorphism:

Why use Polymorphism?

Syntax of Polymorphism (Function Overriding):

class Base {
public:
    virtual void display() {
        cout << "Display from Base" << endl;
    }
};

class Derived : public Base {
public:
    void display() override {
        cout << "Display from Derived" << endl;
    }
};

Example - Function Overriding (Animal → Dog &Cat):

#include <iostream>
#include <string>
using namespace std;

class Animal {
public:
    virtual void sound() {
        cout << "Some generic animal sound." << endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        cout << "Dog says: Woof! Woof!" << endl;
    }
};

class Cat : public Animal {
public:
    void sound() override {
        cout << "Cat says: Meow! Meow!" << endl;
    }
};

int main() {
    Animal* a1 = new Dog();  // pointer of type Animal pointing to Dog
    Animal* a2 = new Cat();  // pointer of type Animal pointing to Cat

    a1->sound();  // calls Dog's sound()
    a2->sound();  // calls Cat's sound()

    delete a1;    // free memory
    delete a2;    // free memory
    return 0;
}

// Output:
// Dog says: Woof! Woof!
// Cat says: Meow! Meow!

8.2.4 Abstraction (ការដកស្រង់) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

What is Abstraction?

Abstraction គឺជាដំណើរការនៃការលាក់ implementation details និងបង្ហាញតែ functionality សំខាន់ៗទៅ user។

Why use Abstraction?

Syntax of Abstraction (Abstract Class):

class AbstractClass {
public:
    // Pure virtual function
    virtual void pureVirtualFunction() = 0;
    
    // Regular virtual function
    virtual void regularFunction() {
        // implementation
    }
};

Example - Abstract Class:

#include <iostream>
#include <string>
using namespace std;

// Abstract Class
class Vehicle {
protected:
    string brand;
    int year;

public:
    Vehicle(string b, int y) : brand(b), year(y) {}

    // Pure virtual functions (ត្រូវតែសរសេរនៅកូន)
    virtual void start() = 0;
    virtual void stop() = 0;
    virtual void displayType() = 0;

    // Function ធម្មតា
    void displayInfo() {
        cout << "Brand: " << brand << ", Year: " << year << endl;
    }
};

// Concrete class - Car
class Car : public Vehicle {
public:
    Car(string b, int y) : Vehicle(b, y) {}

    void start() override {
        cout << "Car is starting..." << endl;
    }
    

    void stop() override {
        cout << "Car is stopping..." << endl;
    }
    
    void displayType() override {
        cout << "Type: Car" << endl;
    }
};

// Concrete class - Motorcycle 
class Motorcycle : public Vehicle {
public:
    Motorcycle(string b, int y) : Vehicle(b, y) {}

    void start() override {
        cout << "Motorcycle is starting..." << endl;
    }
    
    void stop() override {
        cout << "Motorcycle is stopping..." << endl;
    }
    
    void displayType() override {
        cout << "Type: Motorcycle" << endl;
    }
};

int main() {
    Car car("Toyota", 2023);
    Motorcycle moto("Honda", 2022);

    car.displayInfo();
    car.displayType();
    car.start();
    car.stop();

    cout << endl;

    moto.displayInfo();
    moto.displayType();
    moto.start();
    moto.stop();

    return 0;
}

// Output:

// Brand: Toyota, Year: 2023
// Type: Car
// Car is starting...
// Car is stopping...

// Brand: Honda, Year: 2022
// Type: Motorcycle
// Motorcycle is starting...
// Motorcycle is stopping...

8.3 Virtual Functions and Runtime Polymorphism រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Virtual Function

Virtual function គឺជា member function ដែលត្រូវបានប្រកាសដោយប្រើ keyword virtual ក្នុង base class។ វាអនុញ្ញាតឱ្យ derived classes override function នោះ។

class Base {
public:
    virtual void show() {
        cout << "Base class" << endl;
    }
};

Method Overriding

Method Overriding គឺជាការ redefine virtual function ក្នុង derived class។

#include <iostream>
using namespace std;

class Animal {
public:
    virtual void makeSound() {
        cout << "Some animal sound" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "Woof! Woof!" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "Meow! Meow!" << endl;
    }
};

int main() {
    Animal* animal;
    Dog dog;
    Cat cat;
    
    animal = &dog;
    animal->makeSound();  // Calls Dog's version
    
    animal = &cat;
    animal->makeSound();  // Calls Cat's version
    
    return 0;
}

// Output:
// Woof! Woof!
// Meow! Meow!

Base Pointer & Derived Object

Base class pointer អាចកំណត់ទៅកាន់ derived class object។ នេះគឺជាមូលដ្ឋាននៃ runtime polymorphism។

Virtual Destructor

នៅពេលប្រើ polymorphism ជាមួយ pointers គួរតែធ្វើ destructor ជា virtual ដើម្បី ensure proper cleanup។

#include <iostream>
using namespace std;

class Base {
public:
    Base() { cout << "Base Constructor" << endl; }
    virtual ~Base() { cout << "Base Destructor" << endl; }
};

class Derived : public Base {
public:
    Derived() { cout << "Derived Constructor" << endl; }
    ~Derived() { cout << "Derived Destructor" << endl; }
};

int main() {
    Base* ptr = new Derived();
    delete ptr;  // ហៅទាំង Derived និង Base destructors
    
    return 0;
}

// Output:
// Base Constructor
// Derived Constructor
// Derived Destructor
// Base Destructor

Pure Virtual Function

Pure virtual function គឺជា virtual function ដែលគ្មាន implementation ក្នុង base class។ Class ដែលមាន pure virtual function ហៅថា abstract class។

class AbstractClass {
public:
    virtual void pureVirtualFunc() = 0;  // Pure virtual function
};

ឧទាហរណ៍ពេញលេញ:

#include <iostream>
#include <string>
using namespace std;

// Abstract Class 
class Shape {
public:
    // Pure Virtual Function (ត្រូវតែ override នៅកូន class)
    virtual void draw() = 0;

    // Regular Virtual Function (មាន implementation រួច)
    virtual void displayInfo() {
        cout << "This is a Shape" << endl;
    }



    // Normal Function
    void greet() {
        cout << "Hello from Shape!" << endl;
    }
};

// Derived Class 1 
class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};

// Derived Class 2
class Rectangle : public Shape {
public:
    void draw() override {
        cout << "Drawing Rectangle" << endl;
    }

    // Override displayInfo អាចធ្វើក៏បាន
    void displayInfo() override {
        cout << "This is a Rectangle" << endl;
    }
};

int main() {
    // Shape s; // ERROR! មិនអាចបង្កើត Abstract Class បានទេ

    Circle c;
    Rectangle r;

    cout << "===== Circle =====" << endl;
    c.greet();
    c.displayInfo();
    c.draw();

    cout << "===== Rectangle =====" << endl;
    r.greet();
    r.displayInfo();
    r.draw();

    return 0;
}

// Output
// ===== Circle =====
// Hello from Shape!
// This is a Shape
// Drawing Circle
// ===== Rectangle =====
// Hello from Shape!
// This is a Rectangle
// Drawing Rectangle

លំហាត់ប្រចាំមេរៀនទី 8 - OOP

Exercise 1: បង្កើត class Book ដែលមាន encapsulation។ Class គួរមាន private members (title, author, price, ISBN) និង public methods ដើម្បី access និងកែប្រែតម្លៃ។ រួមបញ្ចូល validation សម្រាប់ price (តម្រូវឱ្យ > 0)។

Exercise 2: បង្កើត inheritance hierarchy សម្រាប់ shapes:
- Base class: Shape (abstract) ជាមួយ virtual functions area() និង perimeter()
- Derived classes: Circle, Rectangle, Triangle
- បង្ហាញ polymorphism ដោយប្រើ array of Shape pointers

Exercise 3: សរសេរ BankAccount system ជាមួយ inheritance:
- Base class: Account (accountNumber, balance, basic operations)
- Derived: SavingsAccount (interest rate, calculate interest)
- Derived: CheckingAccount (overdraft limit, fees)
- ប្រើ encapsulation, inheritance, និង polymorphism

Exercise 4: បង្កើត abstract class Media សម្រាប់ library system:
- Pure virtual functions: getTitle(), getType(), displayInfo()
- Derived classes: Book, DVD, Magazine
- Implement library operations (add, search, display all media)

Exercise 5: បង្កើត Complete School Management System ដែលមាន:
- Abstract class Person (name, age, ID)
- Classes: Student (grades, GPA), Teacher (subject, salary), Staff (position, department)
- ប្រើ encapsulation (private data members)
- ប្រើ inheritance (all derive from Person)
- ប្រើ polymorphism (virtual functions)
- ប្រើ abstraction (abstract base class)
- រួមបញ្ចូល menu system ដើម្បី add, display, search persons
- គណនា statistics (average GPA, total salary, etc.)

❖ 9. File Handling in C++

9.1 Introduction to File Handling រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

File Handling ជាដំណើរការសរសេរ (write) ទិន្នន័យទៅកាន់ File ដែលរក្សាទុកនៅលើថាសរឹង ឬអានទិន្នន័យ (read) ចេញពី File។ ខុសពី Variable ធម្មតាដែលទិន្នន័យបាត់ភ្លាមពេលកម្មវិធីបញ្ចប់ File អនុញ្ញាតឲ្យទិន្នន័យនៅតែមានជានិច្ចទោះកម្មវិធីត្រូវបានបិទ។

ហេតុអ្វីត្រូវប្រើ File Handling:

Library ដែលត្រូវការ:
C++ ប្រើ Library ឈ្មោះ <fstream> (File Stream) សម្រាប់ធ្វើការជាមួយ File៖ ត្រូវ #include <fstream> ជានិច្ចមុននឹងប្រើ។

Class សំខាន់ៗក្នុង <fstream>

Classការប្រើប្រាស់
ofstreamOutput File Stream - សម្រាប់សរសេរទិន្នន័យទៅ File
ifstreamInput File Stream - សម្រាប់អានទិន្នន័យពី File
fstreamFile Stream - ធ្វើបានទាំងអាន និងសរសេរក្នុងពេលតែមួយ

9.2 Opening and Closing Files រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

មុននឹងអាន ឬសរសេរ File ណាមួយ ត្រូវតែ "បើក" (open) វាជាមុនសិន ដើម្បីភ្ជាប់ File នោះទៅកម្មវិធី ហើយបន្ទាប់ពីធ្វើការរួច ត្រូវ "បិទ" (close) វាវិញ ដើម្បីធានាថាទិន្នន័យទាំងអស់ត្រូវបានរក្សាទុកឲ្យបានត្រឹមត្រូវ។

Syntax:

// វិធីទី១: បើកតាមរយៈ Constructor ដោយផ្ទាល់
ofstream outFile("filename.txt");

// វិធីទី២: បង្កើត Object ជាមុន រួចហៅ .open() ក្រោយ
ofstream outFile;
outFile.open("filename.txt");

// បិទ File បន្ទាប់ពីប្រើរួច
outFile.close();

ឧទាហរណ៍ - បើក File សរសេរ:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream outFile("notes.txt");

    if (outFile.is_open()) {
        outFile << "ថ្ងៃនេះរៀន File Handling ក្នុង C++";
        outFile.close();
        cout << "សរសេរជោគជ័យ!" << endl;
    } else {
        cout << "មិនអាចបើក File បានទេ!" << endl;
    }
    return 0;
}
សំខាន់! តែងតែត្រូវហៅ .close() បន្ទាប់ពីប្រើ File រួច។ បើមិនធ្វើដូច្នេះទេ ទិន្នន័យខ្លះអាចមិនត្រូវបានរក្សាទុកទាំងស្រុង (ស្ថិតនៅក្នុង Buffer មិនទាន់ចម្លងទៅ File ពិត)។

9.3 Writing to Files រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

ការសរសេរទៅ File ប្រើ Operator << ដូចគ្នានឹងការសរសេរទៅ cout ដែរ ភាពខុសគ្នាគឺគោលដៅ (destination) ប្តូរពី Console ទៅជា File ជំនួសវិញ។

ឧទាហរណ៍ - សរសេរទិន្នន័យសិស្សច្រើននាក់:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    ofstream outFile("students.txt");

    outFile << "សុខា" << " " << 85 << endl;
    outFile << "ដារា" << " " << 92 << endl;
    outFile << "សុភា" << " " << 78 << endl;

    outFile.close();
    cout << "រក្សាទុកទិន្នន័យសិស្សរួចរាល់!" << endl;
    return 0;
}
ចំណាំ៖ endl ដាក់ចូល File ដើម្បីទម្លាក់បន្ទាត់ថ្មី ដូចគ្នានឹងពេលប្រើជាមួយ cout

9.4 Reading from Files រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

ការអានពី File ធ្វើបានពីរវិធីសំខាន់ៗ៖ ប្រើ Operator >> សម្រាប់អានតម្លៃម្តងមួយៗ (ដកឃ្លាបំបែក) ឬប្រើ getline() សម្រាប់អានទាំងបន្ទាត់ (រួមទាំងដកឃ្លា)។

វិធីការប្រើប្រាស់
>>អានតម្លៃម្តងមួយៗ បញ្ឈប់នៅដកឃ្លា ឬបន្ទាត់ថ្មី
getline(file, str)អានទាំងបន្ទាត់ពេញ រួមទាំងដកឃ្លា រហូតដល់ជួប Newline

ឧទាហរណ៍ - អានទាំងបន្ទាត់ (getline):

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {
    ifstream inFile("notes.txt");
    string line;

    if (inFile.is_open()) {
        while (getline(inFile, line)) {
            cout << line << endl;
        }
        inFile.close();
    } else {
        cout << "មិនអាចបើក File បានទេ!" << endl;
    }
    return 0;
}

ឧទាហរណ៍ - អានតម្លៃម្តងមួយៗ (>>):

ifstream inFile("students.txt");
string name;
int score;

while (inFile >> name >> score) {
    cout << name << " បានពិន្ទុ " << score << endl;
}
inFile.close();
គន្លឹះ៖ while (inFile >> name >> score) ដំណើរការគឺពិត (true) ដរាបណានៅមានទិន្នន័យអានបាន ហើយក្លាយជាមិនពិត (false) ដោយស្វ័យប្រវត្តិនៅចុង File គឺមិនចាំបាច់ត្រួតពិនិត្យ EOF ដោយផ្ទាល់ដៃទេ។

9.5 File Modes រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

File Mode កំណត់ថាតើ File ត្រូវបានបើកយ៉ាងណា៖ ជាអក្សរថ្មីលើអក្សរចាស់ (overwrite) បន្ថែមទៅខាងចុង (append) ឬបើកជា Binary។ កំណត់ជា Parameter ទីពីរនៅពេលហៅ .open()

Modeន័យ
ios::inបើកសម្រាប់អាន (លំនាំដើមរបស់ ifstream)
ios::outបើកសម្រាប់សរសេរ (លំនាំដើមរបស់ ofstream, លុបខ្លឹមសារចាស់ចោល)
ios::appបន្ថែមទិន្នន័យទៅខាងចុង File ដោយមិនលុបខ្លឹមសារចាស់
ios::ateបើក File រួចផ្លាស់ទី Cursor ទៅខាងចុងភ្លាមៗ
ios::truncលុបខ្លឹមសារចាស់ទាំងអស់ចោល (ក្លាយជា File ទទេ)
ios::binaryបើកជា Binary Mode (មិនបម្លែងទិន្នន័យទៅជា Text)

ឧទាហរណ៍ - Append Mode (បន្ថែមទិន្នន័យដោយមិនលុបចាស់):

ofstream outFile("notes.txt", ios::app);
outFile << "\nបន្ថែមបន្ទាត់ថ្មីនេះទៅខាងចុង";
outFile.close();
ប្រយ័ត្ន! បើប្រើ ios::out (ឬបើក ofstream ធម្មតាដោយមិនកំណត់ Mode) ខ្លឹមសារចាស់ទាំងអស់ក្នុង File នឹងត្រូវលុបចោលភ្លាមៗ។ ប្រើ ios::app ជំនួសបើចង់រក្សាទិន្នន័យចាស់ទុក។

9.6 Checking File Status រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

មុននឹងអាន/សរសេរ គួរតែពិនិត្យជានិច្ចថា File បានបើកជោគជ័យដែរឬអត់ ព្រោះ File អាចមិនមាន ឬគ្មានសិទ្ធិចូលប្រើ (Permission) ដែលនាំឲ្យកម្មវិធីអាចដំណើរការខុសដោយអ្នកប្រើមិនដឹងខ្លួន។

Methodត្រឡប់ true ពេលណា
.is_open()File ត្រូវបានបើកជោគជ័យ
.eof()Cursor បានទៅដល់ចុង File (End Of File)
.fail()ប្រតិបត្តិការណ៍អាន/សរសេរចុងក្រោយបានបរាជ័យ
.good()Stream មិនមានបញ្ហាអ្វីទាំងអស់ (ផ្ទុយពី fail)
ifstream inFile("data.txt");

if (!inFile.is_open()) {
    cout << "កំហុស៖ រកមិនឃើញ File ឬបើកមិនបាន!" << endl;
    return 1;
}

9.7 Working with Binary Files រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

Binary File រក្សាទុកទិន្នន័យជា Byte ដោយផ្ទាល់ (មិនបម្លែងទៅជា Text ដូច File ធម្មតា) ដែលធ្វើឲ្យទំហំតូចជាង និងលឿនជាង សម្រាប់ទិន្នន័យស្មុគស្មាញដូចជា Struct ឬ Object។

ឧទាហរណ៍ - សរសេរ/អាន Struct ជា Binary:

#include <iostream>
#include <fstream>
using namespace std;

struct Student {
    char name[50];
    int score;
};

int main() {
    Student s1 = {"សុខា", 88};

    // សរសេរ struct ជា Binary
    ofstream outFile("student.dat", ios::binary);
    outFile.write(reinterpret_cast<char*>(&s1), sizeof(s1));
    outFile.close();

    // អាន struct ត្រឡប់មកវិញ
    Student s2;
    ifstream inFile("student.dat", ios::binary);
    inFile.read(reinterpret_cast<char*>(&s2), sizeof(s2));
    inFile.close();

    cout << s2.name << " - " << s2.score << endl;
    return 0;
}
ចំណាំ៖ reinterpret_cast<char*> ត្រូវការ ព្រោះ .write()/.read() ធ្វើការជាមួយ Byte ដោយផ្ទាល់ (char*) មិនមែនប្រភេទទិន្នន័យជាក់លាក់ណាមួយទេ។

9.8 គម្រោងអនុវត្ត (ប្រព័ន្ធកត់ត្រាសិស្ស) រៀបរៀងដោយ: លោក អ៊ុតថា សៀវអុី

Definition (និយមន័យ)

តោះផ្សំចំណុចទាំងអស់ (open, write, read, append, is_open) ធ្វើជាកម្មវិធីតូចមួយ សម្រាប់បន្ថែម និងបង្ហាញកំណត់ត្រាសិស្ស ដោយរក្សាទុកទៅ File ជានិច្ច។

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void addStudent() {
    ofstream outFile("records.txt", ios::app);
    string name;
    int score;

    cout << "ឈ្មោះសិស្ស: ";
    cin >> name;
    cout << "ពិន្ទុ: ";
    cin >> score;

    outFile << name << " " << score << endl;
    outFile.close();
    cout << "បានរក្សាទុក!" << endl;
}

void showAllStudents() {
    ifstream inFile("records.txt");
    string name;
    int score;

    if (!inFile.is_open()) {
        cout << "មិនទាន់មានកំណត់ត្រាទេ!" << endl;
        return;
    }

    cout << "\n--- បញ្ជីសិស្សទាំងអស់ ---" << endl;
    while (inFile >> name >> score) {
        cout << name << " - ពិន្ទុ " << score << endl;
    }
    inFile.close();
}

int main() {
    int choice;
    do {
        cout << "\n1. បន្ថែមសិស្ស\n2. បង្ហាញសិស្សទាំងអស់\n0. ចេញ\nជម្រើស: ";
        cin >> choice;

        if (choice == 1) addStudent();
        else if (choice == 2) showAllStudents();
    } while (choice != 0);

    return 0;
}

លំហាត់អនុវត្ត

  1. សរសេរកម្មវិធីអានឯកសារអត្ថបទមួយ ហើយរាប់ថាមានប៉ុន្មានបន្ទាត់ (line count)។
  2. បន្ថែមមុខងារ "លុបកំណត់ត្រា" ទៅកម្មវិធីខាងលើ (ព័ត៌មានបន្ថែម៖ អានទាំងអស់ចូល Memory, ច្រោះចេញ, សរសេរឡើងវិញទាំងអស់ដោយប្រើ ios::trunc)។
  3. សរសេរកម្មវិធីចម្លងខ្លឹមសារពី File មួយ ទៅ File មួយទៀត (File Copy)។
  4. សាកល្បងប្រើ ios::binary ដើម្បីរក្សាទុក Array នៃ struct ច្រើនក្នុងម្តង រួចអានត្រឡប់មកវិញ។