C and C++ Decision Making: 20 Solved Selection & Switch Case Exercises (Lab 2)

Lab 2 – Programming Practice

C Programming – 10 Unique Tasks

C Task 1: Warehouse Inventory Reorder Alert

Question: Write a C program that checks store warehouse stock levels. Prompt the user to enter current inventory count (integer). Use a single if statement to check if stock is less than 10. If true, display a warning message: “Stock is low! Please issue a reorder request immediately.”

Solution:

#include <stdio.h>

int main() {
    int stockCount;

    printf("Enter current warehouse stock count: ");
    scanf("%d", &stockCount);

    if (stockCount < 10) {
        printf("WARNING: Stock is low! Please issue a reorder request immediately.
");
    }

    printf("Inventory check complete.
");

    return 0;
}

Concept Explanation:

This beginner program introduces the single if statement decision structure from Lab 2. It evaluates a single comparison condition (stockCount < 10) and conditionally executes the warning alert block only when the condition evaluates to true.

C Task 2: Voting Eligibility Verifier

Question: Write a C program to determine voter eligibility. Prompt the user for their age as an integer. Use an if-else statement to check if the age is 18 or older. Display “Eligible to Vote” if true, or “Ineligible to Vote: Minimum age requirement is 18” if false.

Solution:

#include <stdio.h>

int main() {
    int age;

    printf("Enter voter age: ");
    scanf("%d", &age);

    if (age >= 18) {
        printf("Status: Eligible to Vote in national elections.
");
    } else {
        printf("Status: Ineligible to Vote. Minimum age requirement is 18.
");
    }

    return 0;
}

Concept Explanation:

This beginner program practices the fundamental binary if-else decision structure from Lab 2. It evaluates whether the entered age meets the relational condition (age >= 18) and branches execution between two distinct output paths.

C Task 3: Number Divisibility by 5 Evaluator

Question: Write a C program that tests if a given integer is divisible by 5. Prompt the user for an integer number, use an if-else statement with the modulo operator (%), and print whether the number is perfectly divisible by 5 or leaves a remainder.

Solution:

#include <stdio.h>

int main() {
    int number;

    printf("Enter an integer number: ");
    scanf("%d", &number);

    if (number % 5 == 0) {
        printf("%d is perfectly divisible by 5.
", number);
    } else {
        printf("%d is NOT divisible by 5 (Remainder: %d).
", number, number % 5);
    }

    return 0;
}

Concept Explanation:

This beginner program combines the binary if-else structure with the modulo arithmetic operator (%) as taught in Lab 2. It checks if the remainder of division by 5 equals zero to determine mathematical divisibility.

C Task 4: Positive or Negative Number Inspector

Question: Write a C program that prompts the user for an integer. Use a simple if-else statement to check if the number is zero or positive (>= 0) versus negative (< 0), and output the corresponding classification.

Solution:

#include <stdio.h>

int main() {
    int num;

    printf("Enter an integer number: ");
    scanf("%d", &num);

    if (num >= 0) {
        printf("%d is a Positive Number (or Zero).
", num);
    } else {
        printf("%d is a Negative Number.
", num);
    }

    return 0;
}

Concept Explanation:

This beginner task demonstrates a simple binary relational check using if-else from Lab 2. It tests whether an integer is greater than or equal to zero to classify sign orientation.

C Task 5: Day Name Selector

Question: Write a C program that displays the day of the week for a given number (1 to 7). Prompt the user to enter a number (1-7), and use a simple switch statement to print the corresponding day name (1 = Monday, 2 = Tuesday, …, 7 = Sunday).

Solution:

#include <stdio.h>

int main() {
    int day;

    printf("Enter day number (1-7): ");
    scanf("%d", &day);

    switch (day) {
        case 1: printf("Day 1: Monday
"); break;
        case 2: printf("Day 2: Tuesday
"); break;
        case 3: printf("Day 3: Wednesday
"); break;
        case 4: printf("Day 4: Thursday
"); break;
        case 5: printf("Day 5: Friday
"); break;
        case 6: printf("Day 6: Saturday
"); break;
        case 7: printf("Day 7: Sunday
"); break;
        default: printf("Invalid day number! Please enter 1-7.
");
    }

    return 0;
}

Concept Explanation:

This beginner program introduces basic multi-way selection using a switch statement from Lab 2. It maps discrete integer case values to individual day outputs with a default fallback.

C Task 6: Blood Donor Suitability Checker

Question: Write a C program to check blood donor qualification. Prompt for donor age (int) and weight in kg (int). Use nested if-else statements: first verify if age is 18 or older; if true, check if weight is 50 kg or more. Display specific status messages for every case.

Solution:

#include <stdio.h>

int main() {
    int age, weight;

    printf("Enter donor age: ");
    scanf("%d", &age);

    printf("Enter donor weight (kg): ");
    scanf("%d", &weight);

    if (age >= 18) {
        if (weight >= 50) {
            printf("Donor Status: QUALIFIED for blood donation.
");
        } else {
            printf("Donor Status: REJECTED (Minimum required weight is 50 kg).
");
        }
    } else {
        printf("Donor Status: REJECTED (Minimum required age is 18 years).
");
    }

    return 0;
}

Concept Explanation:

This medium task practices nested if-else structures introduced in Lab 2. An outer if condition evaluates age eligibility first, and only when satisfied does the inner if statement test the secondary weight condition.

C Task 7: Employee Performance Bonus Evaluator

Question: Write a C program that calculates performance bonuses. Prompt for an employee rating score between 1 and 100. Use a cascaded if-else if-else structure: score >= 90 receives 20% bonus; score >= 75 receives 10% bonus; score >= 60 receives 5% bonus; otherwise 0% bonus.

Solution:

#include <stdio.h>

int main() {
    int score;
    double baseSalary = 5000.0, bonusPercent = 0.0, bonusAmount;

    printf("Enter employee performance rating score (1-100): ");
    scanf("%d", &score);

    if (score >= 90) {
        bonusPercent = 20.0;
    } else if (score >= 75) {
        bonusPercent = 10.0;
    } else if (score >= 60) {
        bonusPercent = 5.0;
    } else {
        bonusPercent = 0.0;
    }

    bonusAmount = baseSalary * (bonusPercent / 100.0);

    printf("
--- Annual Bonus Evaluation ---
");
    printf("Performance Score: %d
", score);
    printf("Bonus Awarded: %.0lf%%
", bonusPercent);
    printf("Calculated Bonus Amount: $%.2lf
", bonusAmount);

    return 0;
}

Concept Explanation:

This medium program demonstrates the cascaded if-else if-else ladder from Lab 2. It checks multiple mutually exclusive range tiers sequentially from highest score down to default fallback.

C Task 8: Restaurant Meal Menu Order System

Question: Write a C program that displays a restaurant menu: 1. Burger ($8), 2. Pizza ($12), 3. Pasta ($10). Prompt the user for their menu selection (1-3) and item quantity. Use a switch statement to select unit price, calculate total order bill, and handle invalid selections with default.

Solution:

#include <stdio.h>

int main() {
    int choice, quantity;
    double price = 0.0, totalBill;

    printf("=== RESTAURANT MEAL MENU ===
");
    printf("1. Classic Burger  ($8.00)
");
    printf("2. Italian Pizza   ($12.00)
");
    printf("3. Creamy Pasta    ($10.00)
");
    printf("Enter choice (1-3): ");
    scanf("%d", &choice);

    switch (choice) {
        case 1:
            price = 8.00;
            break;
        case 2:
            price = 12.00;
            break;
        case 3:
            price = 10.00;
            break;
        default:
            printf("Invalid menu option selected!
");
            return 0;
    }

    printf("Enter quantity: ");
    scanf("%d", &quantity);

    totalBill = price * quantity;

    printf("
Total Order Cost: $%.2lf
", totalBill);

    return 0;
}

Concept Explanation:

This medium program demonstrates multi-way selection using switch statements from Lab 2. It uses discrete integral constant cases to set prices, break statements to prevent fall-through, and a default case for error handling.

C Task 9: Character Type & Case Classifier

Question: Write a C program that inputs a single character from the user. Use a cascaded if-else structure with ASCII range conditions to identify whether the character is an Uppercase Alphabet letter (‘A’-‘Z’), Lowercase Alphabet letter (‘a’-‘z’), Numeric Digit (‘0’-‘9’), or Special Symbol.

Solution:

#include <stdio.h>

int main() {
    char ch;

    printf("Enter any single character: ");
    scanf(" %c", &ch);

    if (ch >= 'A' && ch <= 'Z') {
        printf("Character '%c' is an UPPERCASE alphabet letter.
", ch);
    } else if (ch >= 'a' && ch <= 'z') {
        printf("Character '%c' is a LOWERCASE alphabet letter.
", ch);
    } else if (ch >= '0' && ch <= '9') {
        printf("Character '%c' is a NUMERIC DIGIT.
", ch);
    } else {
        printf("Character '%c' is a SPECIAL SYMBOL.
", ch);
    }

    return 0;
}

Concept Explanation:

This difficult task practices relational operators and logical AND (&&) within cascaded if-else statements from Lab 2. It compares input character ASCII values against defined character range boundaries.

C Task 10: Cinema Seat Class and Day Pricing System

Question: Write a C program to calculate cinema ticket rates. Prompt user for seat class: 1 for Standard ($10), 2 for VIP ($20). Then ask if it is a weekend (1 for Yes, 0 for No). Use a switch statement for seat class, and an internal if statement inside cases to add a $3 weekend surcharge. Output final price.

Solution:

#include <stdio.h>

int main() {
    int seatClass, isWeekend;
    double basePrice = 0.0, finalPrice;

    printf("=== CINEMA TICKET SYSTEM ===
");
    printf("1. Standard Seat ($10 base)
");
    printf("2. VIP Deluxe Seat ($20 base)
");
    printf("Select seat class (1 or 2): ");
    scanf("%d", &seatClass);

    printf("Is this a weekend show? (1 = Yes, 0 = No): ");
    scanf("%d", &isWeekend);

    switch (seatClass) {
        case 1:
            basePrice = 10.0;
            if (isWeekend == 1) {
                basePrice += 3.0;
            }
            break;
        case 2:
            basePrice = 20.0;
            if (isWeekend == 1) {
                basePrice += 3.0;
            }
            break;
        default:
            printf("Invalid seat class selected!
");
            return 0;
    }

    finalPrice = basePrice;
    printf("
Final Ticket Price: $%.2lf
", finalPrice);

    return 0;
}

Concept Explanation:

This challenging task combines multi-way switch decision logic with embedded if condition checks inside case blocks from Lab 2. It calculates base rates dynamically according to secondary weekend status conditions.

C++ Programming – 10 Unique Tasks

C++ Task 1: Credit Card Overlimit Warning

Question: Write a C++ program that monitors credit card spending limits. Prompt the user for current account balance ($) and credit limit ($). Use a single if statement to check if balance exceeds the limit. If true, display an alert: “ALERT: Credit Limit Exceeded! Surcharge applied.”

Solution:

#include <iostream>
using namespace std;

int main() {
    double balance, creditLimit;

    cout << "Enter current account balance ($): ";
    cin >> balance;

    cout << "Enter assigned credit limit ($): ";
    cin >> creditLimit;

    if (balance > creditLimit) {
        cout << "ALERT: Credit Limit Exceeded! Surcharge applied." << endl;
    }

    cout << "Account monitoring check complete." << endl;

    return 0;
}

Concept Explanation:

This beginner program introduces single condition if logic in C++ from Lab 2. It compares balance against creditLimit and conditionally executes the warning text block only if balance exceeds the allowed limit.

C++ Task 2: Pass/Fail Result Checker

Question: Write a C++ program to check student test results. Prompt the user for a test score out of 100. Use an if-else statement to check if score is 50 or higher. Display “Result: PASSED” for score >= 50, or “Result: FAILED” for score less than 50.

Solution:

#include <iostream>
using namespace std;

int main() {
    double score;

    cout << "Enter student test score (0-100): ";
    cin >> score;

    if (score >= 50.0) {
        cout << "Result: PASSED! Congratulations." << endl;
    } else {
        cout << "Result: FAILED. Needs improvement." << endl;
    }

    return 0;
}

Concept Explanation:

This beginner program practices binary if-else decision statements in C++ based on Lab 2. It evaluates test score against the 50.0 threshold to choose between success or failure output streams.

C++ Task 3: Multiple of 3 Identifier

Question: Write a C++ program to check if an integer is a multiple of 3. Prompt the user for an integer value, evaluate the condition using the modulo operator (%), and print whether the number is a multiple of 3 or not.

Solution:

#include <iostream>
using namespace std;

int main() {
    int num;

    cout << "Enter an integer number: ";
    cin >> num;

    if (num % 3 == 0) {
        cout << num << " is a MULTIPLE of 3." << endl;
    } else {
        cout << num << " is NOT a multiple of 3." << endl;
    }

    return 0;
}

Concept Explanation:

This beginner task practices simple if-else selection in C++ combined with modulo % logic from Lab 2. It checks whether the integer remainder of division by 3 equals zero.

C++ Task 4: Temperature Freezing Point Checker

Question: Write a C++ program to test for freezing temperatures. Prompt the user to enter temperature in Celsius. Use an if-else statement to display “Freezing Warning: Temperature is at or below freezing point!” if temp <= 0, or "Temperature is above freezing." if temp > 0.

Solution:

#include <iostream>
using namespace std;

int main() {
    double temp;

    cout << "Enter temperature in Celsius (°C): ";
    cin >> temp;

    if (temp <= 0.0) {
        cout << "Freezing Warning: Temperature is at or below freezing point!" << endl;
    } else {
        cout << "Temperature is above freezing point." << endl;
    }

    return 0;
}

Concept Explanation:

This beginner task practices binary condition checking using if-else in C++ from Lab 2. It tests whether a floating-point temperature value drops to 0 degrees Celsius or lower.

C++ Task 5: Traffic Light Action Selector

Question: Write a C++ program that simulates a traffic signal light control system. Prompt the user to select color code: 1 for Red, 2 for Yellow, 3 for Green. Use a simple switch statement to display the required driver action (“1: STOP”, “2: SLOW DOWN”, “3: GO”).

Solution:

#include <iostream>
using namespace std;

int main() {
    int colorCode;

    cout << "=== TRAFFIC LIGHT SIGNAL ===" << endl;
    cout << "1. Red Light" << endl;
    cout << "2. Yellow Light" << endl;
    cout << "3. Green Light" << endl;
    cout << "Enter signal code (1-3): ";
    cin >> colorCode;

    switch (colorCode) {
        case 1: cout << "Action: STOP immediately!" << endl; break;
        case 2: cout << "Action: SLOW DOWN and prepare to stop." << endl; break;
        case 3: cout << "Action: GO! Drive safely." << endl; break;
        default: cout << "Invalid signal code!" << endl;
    }

    return 0;
}

Concept Explanation:

This beginner program practices basic switch multi-way decision control in C++ from Lab 2. It evaluates an integer signal code and outputs the corresponding traffic driving instruction.

C++ Task 6: Bank Loan Approval System

Question: Write a C++ program that evaluates loan application criteria. Prompt for applicant monthly income ($) and credit score (300-850). Use nested if-else logic: check if monthly income is at least $3,000; if true, check if credit score is 700 or higher to approve the loan. Display status.

Solution:

#include <iostream>
using namespace std;

int main() {
    double monthlyIncome;
    int creditScore;

    cout << "Enter monthly income ($): ";
    cin >> monthlyIncome;

    cout << "Enter credit score (300-850): ";
    cin >> creditScore;

    if (monthlyIncome >= 3000.0) {
        if (creditScore >= 700) {
            cout << "Loan Approval Status: APPROVED!" << endl;
        } else {
            cout << "Loan Approval Status: REJECTED (Credit score below 700)." << endl;
        }
    } else {
        cout << "Loan Approval Status: REJECTED (Monthly income below $3,000)." << endl;
    }

    return 0;
}

Concept Explanation:

This medium task demonstrates nested if-else conditional branching in C++ from Lab 2. The program enforces sequential evaluation rules by verifying income prerequisites before evaluating credit score metrics.

C++ Task 7: Courier Delivery Shipping Charge Calculator

Question: Write a C++ program to calculate parcel shipping rates based on weight in kg. Prompt for weight and use a cascaded if-else ladder: weight <= 2 kg costs $5; weight <= 5 kg costs $10; weight <= 10 kg costs $20; weight > 10 kg costs $35. Display shipping fee.

Solution:

#include <iostream>
using namespace std;

int main() {
    double weight, shippingFee;

    cout << "Enter package weight in kg: ";
    cin >> weight;

    if (weight <= 2.0) {
        shippingFee = 5.0;
    } else if (weight <= 5.0) {
        shippingFee = 10.0;
    } else if (weight <= 10.0) {
        shippingFee = 20.0;
    } else {
        shippingFee = 35.0;
    }

    cout << "
--- Shipping Fee Summary ---" << endl;
    cout << "Package Weight: " << weight << " kg" << endl;
    cout << "Shipping Fee: $" << shippingFee << endl;

    return 0;
}

Concept Explanation:

This medium program applies cascaded if-else selection structures in C++ from Lab 2. It steps through weight thresholds sequentially to select appropriate flat shipping rates.

C++ Task 8: Bank Currency Exchange Selector

Question: Write a C++ program that offers a currency conversion menu: 1. USD to EUR (0.92 rate), 2. USD to GBP (0.79 rate), 3. USD to JPY (155.0 rate). Prompt the user for option choice and USD amount. Use a switch statement to perform conversion and output result.

Solution:

#include <iostream>
using namespace std;

int main() {
    int choice;
    double usd, converted = 0.0;

    cout << "=== CURRENCY EXCHANGE MENU ===" << endl;
    cout << "1. Convert USD to Euros (EUR)" << endl;
    cout << "2. Convert USD to Pounds (GBP)" << endl;
    cout << "3. Convert USD to Yen (JPY)" << endl;
    cout << "Select option (1-3): ";
    cin >> choice;

    cout << "Enter USD amount ($): ";
    cin >> usd;

    switch (choice) {
        case 1:
            converted = usd * 0.92;
            cout << usd << " USD = " << converted << " EUR" << endl;
            break;
        case 2:
            converted = usd * 0.79;
            cout << usd << " USD = " << converted << " GBP" << endl;
            break;
        case 3:
            converted = usd * 155.0;
            cout << usd << " USD = " << converted << " JPY" << endl;
            break;
        default:
            cout << "Invalid exchange option selected!" << endl;
    }

    return 0;
}

Concept Explanation:

This medium program demonstrates multi-way menu selection in C++ using switch statements from Lab 2. Case labels execute designated exchange formulas based on discrete menu inputs.

C++ Task 9: Water Quality & Chemical Safety Index Classifier

Question: Write a C++ program that classifies water safety based on pH levels (0.0 – 14.0). Prompt for pH value and use cascaded if-else if-else logic: pH 6.5 to 8.5 is “Safe & Optimal”; pH 5.0 to 6.4 or 8.6 to 9.5 is “Moderate Concern”; otherwise “Hazardous / Unsafe”.

Solution:

#include <iostream>
using namespace std;

int main() {
    double ph;

    cout << "Enter water pH value (0.0 - 14.0): ";
    cin >> ph;

    if (ph >= 6.5 && ph <= 8.5) {
        cout << "Water Quality: Safe & Optimal for drinking." << endl;
    } else if ((ph >= 5.0 && ph < 6.5) || (ph > 8.5 && ph <= 9.5)) {
        cout << "Water Quality: Moderate Concern (Treatment recommended)." << endl;
    } else {
        cout << "Water Quality: HAZARDOUS / UNSAFE!" << endl;
    }

    return 0;
}

Concept Explanation:

This difficult program practices cascaded if-else if-else ladders with compound logical operators (&&, ||) in C++ from Lab 2. It categorizes floating-point measurements into environmental safety bands.

C++ Task 10: Vehicle Toll Plaza Surcharge System

Question: Write a C++ program for highway toll rates. Display vehicle menu: 1. Car ($5 base), 2. Truck ($12 base), 3. Bus ($25 base). Prompt for choice, then ask if traveling during peak rush hours (1 = Yes, 0 = No). Use a switch statement for vehicle base rate and add 20% surcharge for peak hours.

Solution:

#include <iostream>
using namespace std;

int main() {
    int vehicleType, isPeak;
    double tollFee = 0.0;

    cout << "=== TOLL PLAZA RATE SYSTEM ===" << endl;
    cout << "1. Passenger Car ($5 base)" << endl;
    cout << "2. Heavy Truck   ($12 base)" << endl;
    cout << "3. Tourist Bus   ($25 base)" << endl;
    cout << "Select vehicle class (1-3): ";
    cin >> vehicleType;

    cout << "Is travel during peak rush hours? (1 = Yes, 0 = No): ";
    cin >> isPeak;

    switch (vehicleType) {
        case 1:
            tollFee = 5.0;
            if (isPeak == 1) tollFee *= 1.20;
            break;
        case 2:
            tollFee = 12.0;
            if (isPeak == 1) tollFee *= 1.20;
            break;
        case 3:
            tollFee = 25.0;
            if (isPeak == 1) tollFee *= 1.20;
            break;
        default:
            cout << "Invalid vehicle type selected!" << endl;
            return 0;
    }

    cout << "
Final Highway Toll Fee: $" << tollFee << endl;

    return 0;
}

Concept Explanation:

This challenging task combines C++ switch multi-way decision logic with conditional if modification statements inside case branches from Lab 2. It calculates base rates dynamically according to peak hour travel surcharges.

Leave a Comment