Practice: Beginner Exercises

Learning to program is like learning to swim -- reading textbooks is no substitute for getting in the water. This lesson ties together the first 9 lessons by having you write 3 complete mini-programs.

Project 1: Celsius to Fahrenheit Converter

This project combines variables, arithmetic, and input/output. The formula is:

F = C x 9 / 5 + 32

Requirements Analysis

Key Concepts

Example

C
#include <stdio.h>

int main(void) {
    double celsius;
    printf("Enter temperature in Celsius: ");
    scanf("%lf", &celsius);

    double fahrenheit = celsius * 9.0 / 5.0 + 32.0;
    double kelvin = celsius + 273.15;

    printf("\n===== Temperature Conversion =====\n");
    printf("Celsius:   %.2f C\n", celsius);
    printf("Fahrenheit:%.2f F\n", fahrenheit);
    printf("Kelvin:    %.2f K\n", kelvin);
    printf("==================================\n");
    return 0;
}
▶ Try it Yourself
TEXT
Enter temperature in Celsius: 36.5

===== Temperature Conversion =====
Celsius:   36.50 C
Fahrenheit:97.70 F
Kelvin:    309.65 K
==================================
💡 Tip: Write 9.0 / 5.0 instead of 9 / 5, because integer division 9/5 equals 1, not 1.8, which would produce incorrect results.

Common Mistakes

  1. Integer division: celsius * 9 / 5 truncates 9/5 to 1 -> write 9.0/5.0 instead
  2. Using %f in scanf for double: double must use %lf; printf can use %f for double
  3. Forgetting &: scanf("%lf", celsius) will crash -> scanf("%lf", &celsius)

Extension Challenge

Can you reverse the conversion -- input Fahrenheit and output Celsius? The formula is C = (F - 32) x 5 / 9.

Project 2: Leap Year Checker

This project combines conditional statements, logical operators, and the modulo operator.

Leap Year Rules

Expressed as a logical condition:

C
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)

Requirements Analysis

Key Concepts

Example

C
#include <stdio.h>

int main(void) {
    int year;
    printf("Enter a year: ");
    scanf("%d", &year);

    if (year <= 0) {
        printf("Error: Year must be a positive integer\n");
        return 1;
    }

    int is_leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    int feb_days = is_leap ? 29 : 28;

    printf("\n===== Result =====\n");
    printf("Year:     %d\n", year);
    printf("Type:     %s\n", is_leap ? "Leap year" : "Common year");
    printf("Feb days: %d\n", feb_days);
    printf("==================\n");
    return 0;
}
▶ Try it Yourself
TEXT
Enter a year: 2000

===== Result =====
Year:     2000
Type:     Leap year
Feb days: 29
==================

Test a few boundary years:

Year Expected Result Reason
2000 Leap year Divisible by 400
1900 Common year Divisible by 100 but not by 400
2024 Leap year Divisible by 4 but not by 100
2023 Common year Not divisible by 4

Step-by-Step Derivation

Beginners often get the leap year condition wrong. Let's derive it step by step:

  1. First step: divisible by 4 -> most likely a leap year
  2. Second step: but century years divisible by 100 are usually not leap years -> add condition "and not divisible by 100"
  3. Third step: but century years divisible by 400 are leap years -> add condition "or divisible by 400"
💡 Tip: Deriving step by step is more reliable than memorizing a formula. For complex conditions, write a simple version first, then add corrections incrementally.

Project 3: Simple Calculator

This project combines switch-case, loops, input/output, and arithmetic operations.

Requirements Analysis

Key Concepts

Example

C
#include <stdio.h>

int main(void) {
    double a, b;
    char op;
    char again;

    do {
        printf("\n===== Simple Calculator =====\n");
        printf("Enter expression (e.g. 3 + 5): ");
        scanf("%lf %c %lf", &a, &op, &b);

        printf("--------------------\n");
        switch (op) {
            case '+':
                printf("%.2f + %.2f = %.2f\n", a, b, a + b);
                break;
            case '-':
                printf("%.2f - %.2f = %.2f\n", a, b, a - b);
                break;
            case '*':
                printf("%.2f * %.2f = %.2f\n", a, b, a * b);
                break;
            case '/':
                if (b == 0) {
                    printf("Error: Division by zero!\n");
                } else {
                    printf("%.2f / %.2f = %.2f\n", a, b, a / b);
                }
                break;
            default:
                printf("Error: Unsupported operator '%c'\n", op);
                break;
        }
        printf("--------------------\n");

        printf("Continue? (Y/N): ");
        scanf(" %c", &again);
    } while (again == 'Y' || again == 'y');

    printf("Goodbye!\n");
    return 0;
}
▶ Try it Yourself
TEXT
===== Simple Calculator =====
Enter expression (e.g. 3 + 5): 10 / 3
--------------------
10.00 / 3.00 = 3.33
--------------------
Continue? (Y/N): Y

===== Simple Calculator =====
Enter expression (e.g. 3 + 5): 5 / 0
--------------------
Error: Division by zero!
--------------------
Continue? (Y/N): N
Goodbye!

Design Highlights

  1. Input format: scanf("%lf %c %lf", &a, &op, &b) reads three values in one call, separated by spaces -- concise and natural
  2. Division-by-zero guard: In case '/', check b == 0 first to avoid a runtime error
  3. Loop control: do-while guarantees at least one calculation; the user chooses whether to continue
  4. Buffer handling: The space before %c in scanf(" %c", &again) skips the leftover newline from previous input

Extension Challenge

Add the modulo operator % to the calculator (note that operands must be integers), and a hint for exponentiation (using the pow function from math.h).

Comprehensive Knowledge Review

These 3 projects cover the core knowledge from the first 9 lessons:

Project Concepts Covered
Temperature Conversion Variables and types, arithmetic, printf formatting, scanf input, integer division trap
Leap Year Checker Modulo, relational operators, logical operators, if-else, ternary operator, input validation
Simple Calculator switch-case, do-while loop, continue, buffer handling, division-by-zero check

General Steps for Writing Good Programs

  1. Understand the requirements: What is the input? What is the output? What are the edge cases?
  2. Choose structures: Which statements to use? if or switch? for or while?
  3. Write pseudocode: Describe the logic in natural language first, then translate to C
  4. Implement incrementally: Write and test as you go; do not write everything at once before debugging
  5. Test thoroughly: Test normal values, boundary values, and invalid values

❓ FAQ

Q Why does scanf need %lf for double but printf uses %f?
A scanf needs to know the exact size of the parameter to write memory correctly; double and float have different sizes. In printf, float is automatically promoted to double, so %f works for both.
Q Is a single logical expression or nested if better for checking leap years?
A A logical expression is more compact for simple conditions; nested if is more readable for complex conditions. Beginners should start with nested if to understand the logic, then simplify to a logical expression.
Q Is comparing b == 0 for a floating-point number reliable?
A Strictly speaking, floating-point numbers should not be compared with ==, but when the user directly inputs 0, it is exactly 0.0. A more rigorous approach is fabs(b) < 1e-10, which requires math.h.
Q What if my program is already wrong halfway through? How do I debug?
A Add printf statements at key points to output intermediate variable values, and gradually narrow down the error. This is called "printf debugging" -- the most basic and effective debugging technique.

📖 Summary

📝 Exercises

  1. Add a reverse conversion feature to the temperature program: enter 1 for Celsius to Fahrenheit, 2 for Fahrenheit to Celsius, using switch or if-else.
  2. Enhance the leap year program to accept a start and end year, then output all leap years in that range (using a for loop).
  3. Add modulo % and integer division to the calculator. Note that modulo requires integer operands, so prompt the user to enter integers.
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏