c
exercises
exercises.c🔧c
/**
* @file exercises.c
* @brief if, else, else if Exercises
*
* Practice decision-making statements in C.
*
* Compile: gcc -Wall exercises.c -o exercises -lm
* Run: ./exercises
*/
#include <stdio.h>
#include <math.h>
/* ============================================================
* EXERCISE 1: CHECK POSITIVE, NEGATIVE, OR ZERO
* ============================================================
* Difficulty: Easy
*
* Task: Complete the function to check if a number is
* positive, negative, or zero.
*/
void checkNumber(int num) {
// TODO: Use if-else if-else to print:
// "Positive" if num > 0
// "Negative" if num < 0
// "Zero" if num == 0
printf("Number %d is: ", num);
// Your code here
}
void exercise_1() {
printf("\n=== Exercise 1: Positive/Negative/Zero ===\n");
checkNumber(10);
checkNumber(-5);
checkNumber(0);
}
/* ============================================================
* EXERCISE 2: FIND MAXIMUM OF THREE NUMBERS
* ============================================================
* Difficulty: Easy
*
* Task: Complete the function to find and return the
* maximum of three numbers using if-else statements.
*/
int findMax(int a, int b, int c) {
// TODO: Return the largest of a, b, c
// Your code here
return 0; // Replace this
}
void exercise_2() {
printf("\n=== Exercise 2: Maximum of Three ===\n");
printf("max(10, 25, 15) = %d\n", findMax(10, 25, 15));
printf("max(5, 5, 5) = %d\n", findMax(5, 5, 5));
printf("max(-1, -5, -3) = %d\n", findMax(-1, -5, -3));
}
/* ============================================================
* EXERCISE 3: LEAP YEAR CHECKER
* ============================================================
* Difficulty: Medium
*
* Task: Complete the function to check if a year is a leap year.
* Rules:
* - Divisible by 4 AND
* - NOT divisible by 100, UNLESS also divisible by 400
*/
int isLeapYear(int year) {
// TODO: Return 1 if leap year, 0 otherwise
// Your code here
return 0; // Replace this
}
void exercise_3() {
printf("\n=== Exercise 3: Leap Year Checker ===\n");
int years[] = {2000, 2020, 2100, 2024, 1900, 2023};
int count = sizeof(years) / sizeof(years[0]);
for (int i = 0; i < count; i++) {
printf("%d: %s\n", years[i],
isLeapYear(years[i]) ? "Leap Year" : "Not Leap Year");
}
}
/* ============================================================
* EXERCISE 4: GRADE CALCULATOR
* ============================================================
* Difficulty: Easy
*
* Task: Complete the function to return the letter grade.
* 90-100: A, 80-89: B, 70-79: C, 60-69: D, below 60: F
*/
char getGrade(int score) {
// TODO: Return the appropriate letter grade
// Handle invalid scores (< 0 or > 100) by returning 'X'
// Your code here
return 'X'; // Replace this
}
void exercise_4() {
printf("\n=== Exercise 4: Grade Calculator ===\n");
int scores[] = {95, 85, 75, 65, 55, 100, 0, -5, 110};
int count = sizeof(scores) / sizeof(scores[0]);
for (int i = 0; i < count; i++) {
printf("Score %3d -> Grade %c\n", scores[i], getGrade(scores[i]));
}
}
/* ============================================================
* EXERCISE 5: VOTING ELIGIBILITY
* ============================================================
* Difficulty: Medium
*
* Task: Complete the function to determine voting eligibility.
* Requirements:
* - Must be 18 or older
* - Must be a citizen (isCitizen = 1)
* - Must be registered (isRegistered = 1)
*/
void checkVotingEligibility(int age, int isCitizen, int isRegistered) {
// TODO: Print appropriate message based on eligibility
// If all conditions met: "Eligible to vote"
// Otherwise, print which requirement(s) failed
// Your code here
}
void exercise_5() {
printf("\n=== Exercise 5: Voting Eligibility ===\n");
printf("Case 1 (age=21, citizen=1, registered=1): ");
checkVotingEligibility(21, 1, 1);
printf("Case 2 (age=16, citizen=1, registered=1): ");
checkVotingEligibility(16, 1, 1);
printf("Case 3 (age=25, citizen=0, registered=1): ");
checkVotingEligibility(25, 0, 1);
printf("Case 4 (age=30, citizen=1, registered=0): ");
checkVotingEligibility(30, 1, 0);
}
/* ============================================================
* EXERCISE 6: TRIANGLE TYPE CHECKER
* ============================================================
* Difficulty: Medium
*
* Task: Determine the type of triangle based on side lengths.
* - Equilateral: all sides equal
* - Isosceles: exactly two sides equal
* - Scalene: all sides different
* - Invalid: if triangle inequality fails
* (sum of any two sides must be greater than third)
*/
void classifyTriangle(int a, int b, int c) {
// TODO: Print the type of triangle or "Invalid triangle"
// Your code here
}
void exercise_6() {
printf("\n=== Exercise 6: Triangle Classifier ===\n");
printf("Sides (5, 5, 5): ");
classifyTriangle(5, 5, 5);
printf("Sides (5, 5, 3): ");
classifyTriangle(5, 5, 3);
printf("Sides (3, 4, 5): ");
classifyTriangle(3, 4, 5);
printf("Sides (1, 2, 10): ");
classifyTriangle(1, 2, 10);
}
/* ============================================================
* EXERCISE 7: CALCULATOR WITH VALIDATION
* ============================================================
* Difficulty: Medium
*
* Task: Perform arithmetic operation with validation.
* Operations: '+', '-', '*', '/'
* Handle division by zero and invalid operators.
*/
void calculate(double a, char op, double b) {
// TODO: Perform operation and print result
// Handle division by zero: print "Error: Division by zero"
// Handle invalid operator: print "Error: Invalid operator"
// Your code here
}
void exercise_7() {
printf("\n=== Exercise 7: Calculator ===\n");
printf("10 + 5 = ");
calculate(10, '+', 5);
printf("10 - 5 = ");
calculate(10, '-', 5);
printf("10 * 5 = ");
calculate(10, '*', 5);
printf("10 / 5 = ");
calculate(10, '/', 5);
printf("10 / 0 = ");
calculate(10, '/', 0);
printf("10 ^ 5 = ");
calculate(10, '^', 5);
}
/* ============================================================
* EXERCISE 8: BMI CALCULATOR
* ============================================================
* Difficulty: Medium
*
* Task: Calculate BMI and return the category.
* BMI = weight / (height * height)
* Categories:
* - BMI < 18.5: Underweight
* - 18.5 <= BMI < 25: Normal
* - 25 <= BMI < 30: Overweight
* - BMI >= 30: Obese
*/
void calculateBMI(double weightKg, double heightM) {
// TODO: Calculate BMI and print category
// Handle invalid input (weight <= 0 or height <= 0)
// Your code here
}
void exercise_8() {
printf("\n=== Exercise 8: BMI Calculator ===\n");
printf("Weight: 70kg, Height: 1.75m -> ");
calculateBMI(70, 1.75);
printf("Weight: 50kg, Height: 1.70m -> ");
calculateBMI(50, 1.70);
printf("Weight: 90kg, Height: 1.65m -> ");
calculateBMI(90, 1.65);
printf("Weight: 110kg, Height: 1.80m -> ");
calculateBMI(110, 1.80);
}
/* ============================================================
* EXERCISE 9: QUADRATIC EQUATION SOLVER
* ============================================================
* Difficulty: Hard
*
* Task: Solve ax² + bx + c = 0
* Calculate discriminant = b² - 4ac
* - If discriminant > 0: Two real roots
* - If discriminant = 0: One real root (repeated)
* - If discriminant < 0: No real roots (complex)
* Handle a = 0 case (linear equation)
*/
void solveQuadratic(double a, double b, double c) {
// TODO: Solve the equation and print the result
// Use sqrt() from math.h for square root
// Your code here
}
void exercise_9() {
printf("\n=== Exercise 9: Quadratic Solver ===\n");
printf("x² - 5x + 6 = 0 -> ");
solveQuadratic(1, -5, 6);
printf("x² - 4x + 4 = 0 -> ");
solveQuadratic(1, -4, 4);
printf("x² + x + 1 = 0 -> ");
solveQuadratic(1, 1, 1);
printf("2x + 4 = 0 (linear) -> ");
solveQuadratic(0, 2, 4);
}
/* ============================================================
* EXERCISE 10: DATE VALIDATOR
* ============================================================
* Difficulty: Hard
*
* Task: Validate a date (day, month, year).
* Consider:
* - Month range: 1-12
* - Days per month (including leap years for February)
* - Year > 0
*/
int isValidDate(int day, int month, int year) {
// TODO: Return 1 if valid date, 0 otherwise
// Hint: Use your isLeapYear function from Exercise 3
// Your code here
return 0; // Replace this
}
void exercise_10() {
printf("\n=== Exercise 10: Date Validator ===\n");
int dates[][3] = {
{15, 6, 2024}, // Valid
{31, 4, 2024}, // Invalid (April has 30 days)
{29, 2, 2024}, // Valid (2024 is leap year)
{29, 2, 2023}, // Invalid (2023 is not leap year)
{0, 5, 2024}, // Invalid (day = 0)
{15, 13, 2024}, // Invalid (month = 13)
{31, 12, 2024} // Valid
};
int count = sizeof(dates) / sizeof(dates[0]);
for (int i = 0; i < count; i++) {
int d = dates[i][0];
int m = dates[i][1];
int y = dates[i][2];
printf("%02d/%02d/%04d: %s\n", d, m, y,
isValidDate(d, m, y) ? "Valid" : "Invalid");
}
}
/* ============================================================
* MAIN FUNCTION
* ============================================================ */
int main() {
printf("╔════════════════════════════════════════════════╗\n");
printf("║ IF, ELSE, ELSE IF - EXERCISES ║\n");
printf("║ Practice decision-making ║\n");
printf("╚════════════════════════════════════════════════╝\n");
// Uncomment exercises as you complete them:
// exercise_1();
// exercise_2();
// exercise_3();
// exercise_4();
// exercise_5();
// exercise_6();
// exercise_7();
// exercise_8();
// exercise_9();
// exercise_10();
printf("\n=== Uncomment exercises in main() to run them ===\n");
return 0;
}
/* ============================================================
* ANSWER KEY
* ============================================================
*
* EXERCISE 1:
* void checkNumber(int num) {
* printf("Number %d is: ", num);
* if (num > 0) {
* printf("Positive\n");
* } else if (num < 0) {
* printf("Negative\n");
* } else {
* printf("Zero\n");
* }
* }
*
* EXERCISE 2:
* int findMax(int a, int b, int c) {
* if (a >= b && a >= c) {
* return a;
* } else if (b >= a && b >= c) {
* return b;
* } else {
* return c;
* }
* }
*
* EXERCISE 3:
* int isLeapYear(int year) {
* if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
* return 1;
* }
* return 0;
* }
*
* EXERCISE 4:
* char getGrade(int score) {
* if (score < 0 || score > 100) return 'X';
* if (score >= 90) return 'A';
* if (score >= 80) return 'B';
* if (score >= 70) return 'C';
* if (score >= 60) return 'D';
* return 'F';
* }
*
* EXERCISE 5:
* void checkVotingEligibility(int age, int isCitizen, int isRegistered) {
* if (age >= 18 && isCitizen && isRegistered) {
* printf("Eligible to vote\n");
* } else {
* if (age < 18) printf("Must be 18 or older. ");
* if (!isCitizen) printf("Must be a citizen. ");
* if (!isRegistered) printf("Must be registered. ");
* printf("\n");
* }
* }
*
* EXERCISE 6:
* void classifyTriangle(int a, int b, int c) {
* if (a + b <= c || b + c <= a || a + c <= b) {
* printf("Invalid triangle\n");
* } else if (a == b && b == c) {
* printf("Equilateral\n");
* } else if (a == b || b == c || a == c) {
* printf("Isosceles\n");
* } else {
* printf("Scalene\n");
* }
* }
*
* EXERCISE 7:
* void calculate(double a, char op, double b) {
* if (op == '+') {
* printf("%.2f\n", a + b);
* } else if (op == '-') {
* printf("%.2f\n", a - b);
* } else if (op == '*') {
* printf("%.2f\n", a * b);
* } else if (op == '/') {
* if (b == 0) {
* printf("Error: Division by zero\n");
* } else {
* printf("%.2f\n", a / b);
* }
* } else {
* printf("Error: Invalid operator\n");
* }
* }
*
* EXERCISE 8:
* void calculateBMI(double weightKg, double heightM) {
* if (weightKg <= 0 || heightM <= 0) {
* printf("Invalid input\n");
* return;
* }
* double bmi = weightKg / (heightM * heightM);
* printf("BMI: %.1f - ", bmi);
* if (bmi < 18.5) {
* printf("Underweight\n");
* } else if (bmi < 25) {
* printf("Normal\n");
* } else if (bmi < 30) {
* printf("Overweight\n");
* } else {
* printf("Obese\n");
* }
* }
*
* EXERCISE 9:
* void solveQuadratic(double a, double b, double c) {
* if (a == 0) {
* if (b == 0) {
* printf("No solution\n");
* } else {
* printf("x = %.2f (linear)\n", -c / b);
* }
* return;
* }
* double discriminant = b * b - 4 * a * c;
* if (discriminant > 0) {
* double x1 = (-b + sqrt(discriminant)) / (2 * a);
* double x2 = (-b - sqrt(discriminant)) / (2 * a);
* printf("x1 = %.2f, x2 = %.2f\n", x1, x2);
* } else if (discriminant == 0) {
* double x = -b / (2 * a);
* printf("x = %.2f (repeated)\n", x);
* } else {
* printf("No real roots\n");
* }
* }
*
* EXERCISE 10:
* int isValidDate(int day, int month, int year) {
* if (year <= 0 || month < 1 || month > 12 || day < 1) {
* return 0;
* }
* int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
* if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
* daysInMonth[1] = 29; // February in leap year
* }
* return day <= daysInMonth[month - 1];
* }
*
* ============================================================
*/