Bài tập C/C++ cho người mới

Find the Largest Array Value

Bài tập nhập môn này giúp luyện cú pháp cốt lõi và tư duy giải quyết vấn đề qua Find the Largest Array Value.

Find the Largest Array Value là gì?

Bài tập nhập môn này giúp luyện cú pháp cốt lõi và tư duy giải quyết vấn đề qua Find the Largest Array Value.

Giải bài Find the Largest Array Value bằng cả C và C++ với code có thể chạy.

Điểm quan trọng

  • Luôn bật compiler warning và xử lý mọi cảnh báo.
  • Hiểu rõ type và lifetime của từng giá trị.
  • Kiểm tra input và giới hạn mảng rõ ràng.

Code ví dụ bằng C và C++

C
Chạy code →
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);
}
Output dự kiến
max=23
C++
Chạy code →
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';
}
Output dự kiến
max=23

So sánh C và C++

So sánh implementation C và C++, sau đó thay đổi input và kiểm tra thêm các edge case.

C

C dùng API thủ tục nhỏ gọn và thể hiện chi tiết biểu diễn rõ ràng.

C++

C++ giữ mô hình low-level nhưng bổ sung type thư viện và abstraction an toàn hơn.

Bài tập mở rộng

Chạy cả hai phiên bản rồi thay đổi để quan sát khác biệt về bảo đảm của từng ngôn ngữ.

  • Thêm input sai và boundary value.
  • Biên dịch với -Wall -Wextra -Wpedantic.
  • Tách declaration dùng lại vào header và implementation file.