แบบฝึกหัด C/C++ สำหรับผู้เริ่มต้น

Fibonacci Sequence

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Fibonacci Sequence

Fibonacci Sequence คืออะไร?

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Fibonacci Sequence

แก้โจทย์ Fibonacci Sequence ด้วย code C และ C++ ที่รันได้

ประเด็นสำคัญ

  • เปิด compiler warning และแก้ทุกคำเตือน
  • รู้ type และ lifetime ของทุกค่า
  • ตรวจ input และขอบเขต array ให้ชัดเจน

ตัวอย่างโค้ด C และ C++

C
รันโค้ด →
main.c
#include <stdio.h>
int main(void) {
    int first = 0, second = 1;
    for (int i = 0; i < 10; ++i) {
        printf("%s%d", i ? " " : "", first);
        // Advance the pair without storing the whole sequence.
        int next = first + second; first = second; second = next;
    }
    puts("");
}
ผลลัพธ์ที่คาดหวัง
0 1 1 2 3 5 8 13 21 34
C++
รันโค้ด →
main.cpp
#include <iostream>
int main() {
    int first = 0, second = 1;
    for (int i = 0; i < 10; ++i) {
        if (i) std::cout << ' ';
        std::cout << first;
        // Advance the pair without storing the whole sequence.
        int next = first + second; first = second; second = next;
    }
    std::cout << '\n';
}
ผลลัพธ์ที่คาดหวัง
0 1 1 2 3 5 8 13 21 34

เปรียบเทียบ C และ C++

เปรียบเทียบ implementation ของ C และ C++ จากนั้นเปลี่ยน input และทดสอบ edge case เพิ่มเติม

C

C แสดง API แบบ procedural และรายละเอียด representation อย่างชัดเจน

C++

C++ รักษา low-level model และเพิ่ม type ที่ปลอดภัยกว่า

แบบฝึกหัด

รันทั้งสองเวอร์ชันแล้วแก้ไขเพื่อสังเกตความแตกต่างของภาษา

  • เพิ่ม input ผิดและค่าขอบเขต
  • Compile ด้วย -Wall -Wextra -Wpedantic
  • แยก declaration และ implementation