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

Find the Largest Array Value

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Find the Largest Array Value

Find the Largest Array Value คืออะไร?

แบบฝึกหัดสำหรับผู้เริ่มต้นนี้ฝึก syntax หลักและการแก้ปัญหาผ่าน Find the Largest Array Value

แก้โจทย์ Find the Largest Array Value ด้วย code C และ C++ ที่รันได้

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

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

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

C
รันโค้ด →
main.c
#include <stdio.h>
int main(void) {
    int values[] = {-4, 7, 23, 9, 12}; int maximum = values[0];
    // Compare every remaining value with the current maximum.
    for (size_t i = 1; i < sizeof values / sizeof values[0]; ++i)
        if (values[i] > maximum) maximum = values[i];
    printf("max=%d\n", maximum);
}
ผลลัพธ์ที่คาดหวัง
max=23
C++
รันโค้ด →
main.cpp
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
    std::vector values{-4, 7, 23, 9, 12};
    // max_element returns an iterator to the largest value.
    std::cout << "max=" << *std::max_element(values.begin(), values.end()) << '\n';
}
ผลลัพธ์ที่คาดหวัง
max=23

เปรียบเทียบ 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