Bài tập lập trình C cơ bản với các ví dụ minh họa

Hiển thị hình dạng đơn giản

#include <stdio.h>
int main() {
    puts(" 0 ");
    puts("<H>");
    puts("I I");
    system("pause");
    return 0;
}

Vẽ hai hình song song

#include <stdio.h>
int main() {
    printf(" 0      0\n");
    printf("<H     <H>\n");
    printf("I I    I I\n");
    return 0;
}

Kiểm tra điều kiện tam giác

#include <stdio.h>
int main() {
    double side1, side2, side3;
    scanf("%lf %lf %lf", &side1, &side2, &side3);
    if (side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1)
        printf("Có thể tạo thành tam giác\n");
    else
        printf("Không thể tạo thành tam giác\n");
    return 0;
}

Khảo sát thói quen học tập

#include <stdio.h>
int main() {
    char prep, practice;
    printf("Bạn có ôn bài trước và sau giờ học không? (y/Y = có, n/N = không): ");
    prep = getchar();
    getchar(); // tiêu thụ ký tự newline
    printf("Bạn có thực hành gõ code không?: ");
    practice = getchar();
    if ((prep == 'y' || prep == 'Y') && (practice == 'y' || practice == 'Y'))
        printf("\nThành Rome không xây trong một ngày — hãy tiếp tục!\n");
    else
        printf("\nRome không sụp đổ trong một ngày — hãy bắt đầu xây dựng!\n");
    return 0;
}

Nhập và in nhiều kiểu dữ liệu

#include <stdio.h>
int main() {
    int num1, num2, num3;
    char ch1, ch2, ch3;
    double val1, val2;

    scanf("%d %d %d", &num1, &num2, &num3);
    printf("num1=%d, num2=%d, num3=%d\n", num1, num2, num3);

    scanf(" %c %c %c", &ch1, &ch2, &ch3); // chú ý khoảng trắng trước %c
    printf("ch1='%c', ch2='%c', ch3='%c'\n", ch1, ch2, ch3);

    scanf("%lf,%lf", &val1, &val2);
    printf("val1=%.2f, val2=%.2f\n", val1, val2);
    return 0;
}

Tính số năm tương ứng với 1 tỷ giây

#include <stdio.h>
int main() {
    const double billion_seconds = 1e9;
    int years = (int)(billion_seconds / (365.0 * 24 * 3600) + 0.5);
    printf("1 tỷ giây xấp xỉ bằng %d năm\n", years);
    return 0;
}

Tính lũy thừa 365 của số thực

#include <stdio.h>
#include <math.h>
int main() {
    double base, result;
    while (scanf("%lf", &base) != EOF) {
        result = pow(base, 365);
        printf("%.2f^365 = %.2f\n\n", base, result);
    }
    return 0;
}

Chuyển đổi nhiệt độ Celsius sang Fahrenheit

#include <stdio.h>
int main() {
    double celsius, fahrenheit;
    while (scanf("%lf", &celsius) != EOF) {
        fahrenheit = 9.0 / 5 * celsius + 32;
        printf("%.2f°C = %.2f°F\n\n", celsius, fahrenheit);
    }
    return 0;
}

Tính diện tích tam giác theo công thức Heron

#include <stdio.h>
#include <math.h>
int main() {
    double a, b, c, semi, area;
    while (scanf("%lf %lf %lf", &a, &b, &c) != EOF) {
        semi = (a + b + c) / 2.0;
        area = sqrt(semi * (semi - a) * (semi - b) * (semi - c));
        printf("a=%.0f, b=%.0f, c=%.0f → diện tích = %.3f\n", a, b, c, area);
    }
    return 0;
}

Thẻ: C stdio.h math.h getchar scanf

Đăng vào ngày 24 tháng 6 lúc 22:48