Conditionals in C exercises — master if, else and switch
Conditionals in C exercises are where the syntax stops feeling foreign. You’ve seen the theory and built three complete programs. Now it’s time to solve challenges on your own in Fedora — including a triangle classifier, a login system with attempts, and a final challenge that mixes everything.
Set up your workspace:
cd ~/GCID/IC2/Labs mkdir exercises_conditionals cd exercises_conditionals
As always: try to solve it in gedit, compile with gcc, use the hint if stuck for more than 10 minutes, and compare with the commented solution.
Table of Contents
Conditionals in C exercises — Basic Level
Exercise 1 — Triangle classifier
Write a C program that reads the three sides of a triangle and classifies it. First check if it actually forms a valid triangle, then classify its type.
A valid triangle requires: each side must be less than the sum of the other two.
Classification: All three sides equal → Equilateral Exactly two sides equal → Isosceles All three sides different → Scalene All angles 90°? → Right triangle (use a² + b² = c²)
The output should look like this:
=== TRIANGLE CLASSIFIER === Side A: 3 Side B: 4 Side C: 5 --- Results --- Valid triangle: Yes Type: Scalene Right triangle: Yes (3² + 4² = 5²) Perimeter: 12.00
💡 Hints:
- Read three
doublevalues withscanf("%lf", &a) - Triangle validity:
a < b + c && b < a + c && c < a + b - Equilateral:
a == b && b == c - Isosceles:
a == b || b == c || a == c(but not all three equal) - Right triangle: check if
a*a + b*b == c*cORa*a + c*c == b*bORb*b + c*c == a*a - For doubles, exact
==comparison can fail due to floating point precision — use(a*a + b*b - c*c) < 0.001instead
Exercise 2 — Grade scale converter
Write a C program that reads a grade on the Spanish 0-10 scale and converts it to three other systems: percentage (0-100), GPA (0-4.0) and US letter grade.
Conversion table:
0-10 Spain 0-100 % GPA Letter 9-10 90-100 3.5-4.0 A 7-8.9 70-89 2.5-3.4 B 5-6.9 50-69 1.5-2.4 C 3-4.9 30-49 1.0-1.4 D 0-2.9 0-29 0-0.9 F
=== GRADE CONVERTER === Grade (0-10): 7.5 --- Conversions --- Spain (0-10): 7.50 Percentage: 75.0% GPA (0-4.0): 3.00 Letter grade: B Classification: Merit
💡 Hints:
- Percentage =
grade * 10 - GPA approximation: A→4.0, B→3.0, C→2.0, D→1.0, F→0.0 — or calculate proportionally
- Use
if/else iffor the grade ranges —switchdoesn’t work with doubles - Use a
char lettervariable andswitch (letter)for the feedback message
Conditionals in C exercises — Intermediate Level
Exercise 3 — Login system with attempts
Write a C program that simulates a basic login system. The user has 3 attempts to enter the correct username and password. After 3 failed attempts the account is locked.
Use these hardcoded credentials:
Username: sergio Password: gcid2025
=== LOGIN SYSTEM === Attempt 1 of 3 Username: sergio Password: wrongpass Access denied — incorrect credentials Attempt 2 of 3 Username: sergio Password: gcid2025 Access granted — welcome, sergio!
Or after 3 failures:
Attempt 3 of 3 Username: admin Password: 1234 Access denied — incorrect credentials Account locked — too many failed attempts Contact your administrator
💡 Hints:
- Use
char username[50]andchar password[50] - Compare strings with
strcmp()— requires#include <string.h>. Returns 0 if equal strcmp(username, "sergio") == 0checks if username matches- Use a
do { } whileloop with an attempts counter - Use an
int logged_in = 0flag — set to 1 when login succeeds - Both username AND password must match: use
&&
Conditionals in C exercises — Final Challenge
Exercise 4 — Complete tax calculator
Write a C program that calculates income tax for different types of taxpayer. Ask for: taxpayer type (1=employee, 2=self-employed, 3=company), annual gross income, and number of dependants.
Tax rates by type:
Employee: same brackets as Exercise 2 from types article Self-employed: add 5% to each bracket (extra social security) Company: flat 25% rate (or 15% if income < €1,000,000)
Deductions:
Per dependant: €2,000 deduction from taxable income
=== TAX CALCULATOR === Taxpayer type: 1. Employee 2. Self-employed 3. Company Option: 1 Gross income (€): 35000 Number of dependants: 2 --- Tax Calculation --- Taxpayer type: Employee Gross income: 35000.00 € Deductions: 4000.00 € (2 dependants x 2000 €) Taxable income: 31000.00 € Tax bracket: 30% Tax: 9300.00 € Net income: 21700.00 € Monthly net: 1808.33 €
💡 Hints:
- Use
switchfor the taxpayer type — 3 exact integer values - Use
if/else iffor the tax brackets — ranges with doubles - Deductions:
deduction = dependants * 2000.0 - Taxable income:
taxable = income - deduction— check it doesn’t go negative - For self-employed: add 5 to the bracket percentage before calculating
- For company: simple
if (income < 1000000)→ 15%, else → 25%
Commented solutions
Solution Exercise 1
#include <stdio.h>
int main() {
double a, b, c;
double diff;
printf("=== TRIANGLE CLASSIFIER ===\n\n");
printf("Side A: ");
scanf("%lf", &a);
printf("Side B: ");
scanf("%lf", &b);
printf("Side C: ");
scanf("%lf", &c);
printf("\n--- Results ---\n");
/* Validate triangle */
if (a <= 0 || b <= 0 || c <= 0) {
printf("Error: all sides must be positive\n");
return 1;
}
if (a >= b + c || b >= a + c || c >= a + b) {
printf("Valid triangle: No\n");
printf("These sides cannot form a triangle\n");
return 1;
}
printf("Valid triangle: Yes\n");
/* Classify by sides */
printf("Type: ");
if (a == b && b == c) {
printf("Equilateral\n");
} else if (a == b || b == c || a == c) {
printf("Isosceles\n");
} else {
printf("Scalene\n");
}
/* Check right triangle using floating point safe comparison */
double aa = a*a, bb = b*b, cc = c*c;
int is_right = 0;
if ((aa + bb - cc) < 0.001 && (aa + bb - cc) > -0.001)
is_right = 1;
else if ((aa + cc - bb) < 0.001 && (aa + cc - bb) > -0.001)
is_right = 1;
else if ((bb + cc - aa) < 0.001 && (bb + cc - aa) > -0.001)
is_right = 1;
if (is_right) {
printf("Right triangle: Yes\n");
} else {
printf("Right triangle: No\n");
}
printf("Perimeter: %.2f\n", a + b + c);
return 0;
}
Solution Exercise 2
#include <stdio.h>
int main() {
double grade;
char letter;
double percentage, gpa;
printf("=== GRADE CONVERTER ===\n\n");
printf("Grade (0-10): ");
scanf("%lf", &grade);
if (grade < 0 || grade > 10) {
printf("Error: grade must be between 0 and 10\n");
return 1;
}
percentage = grade * 10;
/* Determine letter and GPA */
if (grade >= 9.0) {
letter = 'A';
gpa = 4.0;
} else if (grade >= 7.0) {
letter = 'B';
gpa = 3.0;
} else if (grade >= 5.0) {
letter = 'C';
gpa = 2.0;
} else if (grade >= 3.0) {
letter = 'D';
gpa = 1.0;
} else {
letter = 'F';
gpa = 0.0;
}
printf("\n--- Conversions ---\n");
printf("Spain (0-10): %.2f\n", grade);
printf("Percentage: %.1f%%\n", percentage);
printf("GPA (0-4.0): %.2f\n", gpa);
printf("Letter grade: %c\n", letter);
printf("\nClassification: ");
switch (letter) {
case 'A': printf("Outstanding\n"); break;
case 'B': printf("Merit\n"); break;
case 'C': printf("Passed\n"); break;
case 'D': printf("Near miss\n"); break;
case 'F': printf("Failed\n"); break;
}
return 0;
}
Solution Exercise 3
#include <stdio.h>
#include <string.h>
int main() {
const char CORRECT_USER[] = "sergio";
const char CORRECT_PASS[] = "gcid2025";
const int MAX_ATTEMPTS = 3;
char username[50];
char password[50];
int attempts = 0;
int logged_in = 0;
printf("=== LOGIN SYSTEM ===\n\n");
do {
attempts++;
printf("Attempt %d of %d\n", attempts, MAX_ATTEMPTS);
printf("Username: ");
scanf("%s", username);
printf("Password: ");
scanf("%s", password);
if (strcmp(username, CORRECT_USER) == 0 &&
strcmp(password, CORRECT_PASS) == 0) {
printf("Access granted — welcome, %s!\n", username);
logged_in = 1;
} else {
printf("Access denied — incorrect credentials\n\n");
}
} while (!logged_in && attempts < MAX_ATTEMPTS);
if (!logged_in) {
printf("\nAccount locked — too many failed attempts\n");
printf("Contact your administrator\n");
}
return 0;
}
Solution Exercise 4
#include <stdio.h>
int main() {
int type, dependants;
double income, deduction, taxable, rate, tax, net, monthly;
printf("=== TAX CALCULATOR ===\n\n");
printf("Taxpayer type:\n");
printf("1. Employee\n");
printf("2. Self-employed\n");
printf("3. Company\n");
printf("Option: ");
scanf("%d", &type);
if (type < 1 || type > 3) {
printf("Invalid option\n");
return 1;
}
printf("\nGross income (€): ");
scanf("%lf", &income);
printf("Number of dependants: ");
scanf("%d", &dependants);
/* Deductions */
deduction = dependants * 2000.0;
taxable = income - deduction;
if (taxable < 0) taxable = 0;
/* Calculate rate */
switch (type) {
case 1: /* Employee */
if (taxable <= 12450) rate = 19;
else if (taxable <= 20200) rate = 24;
else if (taxable <= 35200) rate = 30;
else if (taxable <= 60000) rate = 37;
else rate = 45;
break;
case 2: /* Self-employed — add 5% */
if (taxable <= 12450) rate = 24;
else if (taxable <= 20200) rate = 29;
else if (taxable <= 35200) rate = 35;
else if (taxable <= 60000) rate = 42;
else rate = 50;
break;
case 3: /* Company */
rate = (income < 1000000) ? 15 : 25;
break;
}
tax = taxable * rate / 100.0;
net = income - tax;
monthly = net / 12.0;
/* Taxpayer type name */
const char *type_name;
switch (type) {
case 1: type_name = "Employee"; break;
case 2: type_name = "Self-employed"; break;
case 3: type_name = "Company"; break;
default: type_name = "Unknown";
}
printf("\n--- Tax Calculation ---\n");
printf("Taxpayer type: %s\n", type_name);
printf("Gross income: %9.2f €\n", income);
printf("Deductions: %9.2f € (%d dependants x 2000 €)\n",
deduction, dependants);
printf("Taxable income: %9.2f €\n", taxable);
printf("Tax bracket: %.0f%%\n", rate);
printf("Tax: %9.2f €\n", tax);
printf("Net income: %9.2f €\n", net);
printf("Monthly net: %9.2f €\n", monthly);
return 0;
}
Visualise with Python Tutor
Select C from the dropdown and paste in pythontutor.com:
#include <stdio.h>
int main() {
double grade = 7.5;
char letter;
if (grade >= 9.0) letter = 'A';
else if (grade >= 7.0) letter = 'B';
else if (grade >= 5.0) letter = 'C';
else letter = 'F';
switch (letter) {
case 'A': printf("Outstanding\n"); break;
case 'B': printf("Merit\n"); break;
case 'C': printf("Passed\n"); break;
case 'F': printf("Failed\n"); break;
}
return 0;
}
Step through it and observe how if/else if evaluates conditions one by one until grade 7.5 matches >= 7.0 and assigns 'B' to letter. Then watch switch jump directly to case 'B' — no evaluation of ‘A’, just an immediate jump. This is the key performance difference between the two: if/else if checks each condition in sequence, switch jumps directly. For large menus, switch is noticeably faster.
Cheat sheet — Conditionals in C
/* ============================================
CHEAT SHEET — Conditionals in C
Sergio Learns · sergiolearns.com
============================================ */
/* IF/ELSE IF/ELSE */
if (condition) {
/* condition is true */
} else if (other_condition) {
/* other_condition is true */
} else {
/* nothing matched */
}
/* MANDATORY RULES */
/* 1. Condition in parentheses: if (x > 5) */
/* 2. Always use { } — prevents classic trap */
/* 3. == to compare, = to assign */
/* 4. Python elif = C else if (two words) */
/* COMPARISON OPERATORS */
== != > < >= <=
/* LOGICAL OPERATORS */
/* Python: and or not */
/* C: && || ! */
if (a > 0 && b > 0) /* both must be true */
if (a > 0 || b > 0) /* at least one true */
if (!active) /* inverts boolean */
/* TERNARY OPERATOR */
/* type var = (condition) ? val_true : val_false; */
printf("%s\n", (grade >= 5) ? "Pass" : "Fail");
/* SWITCH — int or char only, not double */
switch (variable) {
case value1:
/* code */
break; /* required — no break = fall-through */
case value2:
case value3: /* multiple cases, same action */
/* code */
break;
default:
/* no case matched */
}
/* SWITCH vs IF/ELSE */
/* switch → exact int/char values, 3+ cases, faster */
/* if/else → ranges, doubles, complex conditions */
/* THE = vs == TRAP IN C */
if (x = 5) /* assigns 5 to x, always true — BUG */
if (x == 5) /* compares — correct */
/* gcc -Wall catches this with a warning */
/* Defensive style: put constant on left */
if (5 == x) /* if you write = instead, compile error */
/* WITHOUT CURLY BRACES — TRAP */
if (x > 5)
printf("A\n");
printf("B\n"); /* always executes — NOT in the if */
/* WITH CURLY BRACES — CORRECT */
if (x > 5) {
printf("A\n");
printf("B\n"); /* correctly inside the if */
}
/* STRING COMPARISON */
#include <string.h>
strcmp(s1, s2) == 0 /* strings are equal */
strcmp(s1, s2) != 0 /* strings are different */
/* NEVER: s1 == s2 for strings */
/* VALIDATE INPUT PATTERN */
if (value < MIN || value > MAX) {
printf("Error: out of range\n");
return 1; /* 0 = success, non-zero = error */
}
/* CLASSIFICATION PATTERN */
if (grade >= 9.0) letter = 'A';
else if (grade >= 7.0) letter = 'B';
else if (grade >= 5.0) letter = 'C';
else letter = 'F';
/* then use switch on letter for messages */
/* COMPILE AND RUN */
/* gcc exercises.c -o exercises -Wall */
/* ./exercises */

One Comment