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
- Input: temperature in Celsius (may be a decimal)
- Output: corresponding temperature in Fahrenheit, rounded to 1 decimal place
- Extension: also output the Kelvin temperature (K = C + 273.15)
Key Concepts
doubletype for storing floating-point numbersscanf("%lf")to read a double-precision floating-point numberprintf("%.1f")to control decimal places- Operator precedence in arithmetic expressions
Example
#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;
}
Enter temperature in Celsius: 36.5
===== Temperature Conversion =====
Celsius: 36.50 C
Fahrenheit:97.70 F
Kelvin: 309.65 K
==================================
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
- Integer division:
celsius * 9 / 5truncates9/5to 1 -> write9.0/5.0instead - Using
%finscanffordouble:doublemust use%lf;printfcan use%ffordouble - 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
- Divisible by 4 but not by 100 -> leap year
- Divisible by 400 -> also a leap year
- Otherwise -> common year
Expressed as a logical condition:
(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
Requirements Analysis
- Input: a positive integer representing a year
- Output: whether the year is a leap year or common year, and the number of days in February
- Defensive check: handle invalid input (negative numbers or zero)
Key Concepts
- Modulo
%to check divisibility - Logical operators
&&,||to combine conditions if-else if-elsemulti-branch structure- Input validation
Example
#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;
}
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:
- First step: divisible by 4 -> most likely a leap year
- Second step: but century years divisible by 100 are usually not leap years -> add condition "and not divisible by 100"
- Third step: but century years divisible by 400 are leap years -> add condition "or divisible by 400"
Project 3: Simple Calculator
This project combines switch-case, loops, input/output, and arithmetic operations.
Requirements Analysis
- Input: two numbers and an operator (+ - * /)
- Output: the calculation result
- Defensive check: display a message when dividing by zero
- Loop: ask whether to continue after each calculation
Key Concepts
switch-caseto handle operatorsdo-whilefor repeated calculations- Division-by-zero check
- Formatted output alignment
continueto skip invalid operations
Example
#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;
}
===== 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
- Input format:
scanf("%lf %c %lf", &a, &op, &b)reads three values in one call, separated by spaces -- concise and natural - Division-by-zero guard: In
case '/', checkb == 0first to avoid a runtime error - Loop control:
do-whileguarantees at least one calculation; the user chooses whether to continue - Buffer handling: The space before
%cinscanf(" %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
- Understand the requirements: What is the input? What is the output? What are the edge cases?
- Choose structures: Which statements to use? if or switch? for or while?
- Write pseudocode: Describe the logic in natural language first, then translate to C
- Implement incrementally: Write and test as you go; do not write everything at once before debugging
- Test thoroughly: Test normal values, boundary values, and invalid values
❓ FAQ
scanf need %lf for double but printf uses %f?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.b == 0 for a floating-point number reliable?==, 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.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
- Writing complete programs is the fastest way to master C; reading alone will not get you there
- Integer division is the most common pitfall in floating-point arithmetic -- make sure at least one operand is written as a decimal
- Derive complex conditions step by step: write the base rule first, then add corrections
- switch-case paired with do-while is the classic pattern for interactive menus
- General programming workflow: understand requirements -> choose structures -> write pseudocode -> implement -> test
📝 Exercises
- 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.
- Enhance the leap year program to accept a start and end year, then output all leap years in that range (using a for loop).
- Add modulo
%and integer division to the calculator. Note that modulo requires integer operands, so prompt the user to enter integers.



