Scenario-Based Coding Questions on If-else in C++

c++ if else scenario based questions

The best way to learn programming is by rolling up your sleeves and doing it! In fact, recent learning studies (2025–2026) show that students improve problem-solving skills by up to 60% faster when practicing real-world scenarios instead of only theory. Time to solve some interesting scenario-based coding problems around real-world problems with engaging visuals to imagine the scenario. These questions are based on conditonal statements in C++ that covers If, If-else, If-else-if along with taking input from a user in C++ for making interactive and user-friendly programs.

Outfit Suggestion Based on Weather

Scenario Based question weather report in if-else condition in c++
On a beautiful day, you need to decide what to wear. Write a program that takes the current temperature as input and suggests the appropriate clothing. If the temperature is above 25°C, recommend wearing a shirt; otherwise, recommend wearing a jacket.

Test Case:
Input: 30
Expected Output: “Wear a shirt.”

Explanation:

This program uses a simple if-else statement to determine the clothing suggestion based on the temperature input. The if statement checks if the temperature is greater than 25°C. If true, it suggests wearing a shirt. If the temperature is 25°C or below, the else statement suggests wearing a jacket.

  • The program starts by asking the user to enter the current temperature in Celsius, which is stored in the temperature variable.
  • The program checks if the temperature is greater than 25°C (temperature > 25).
    • If true, it suggests wearing a shirt by printing “Wear a shirt.”
  • If the condition is not true, the else block executes and the program prints the message “Wear a jacket.”
#include <iostream>
using namespace std;

int main() {
int temperature;

// Prompting the user to input the current temperature
cout << "Enter the current temperature in °C: ";
cin >> temperature;

// Providing outfit suggestions based on the temperature
if (temperature > 25) {
cout << "Wear a shirt.\n";
} else {
cout << "Wear a jacket.\n";
}

return 0;
}

Amusement Park Ride

conditional statements in If else scenario based questions amusement ride
 You’re at an amusement park, and you want to know if you can ride a roller coaster. The park requires that riders must be at least 120 cm tall. Write a program that takes your height as input and tells you whether you can ride the roller coaster.

Test Case:
Input: 130
Expected Output: “You can ride the roller coaster!”

Explanation:

This program uses an if-else condition to check whether the user’s height meets the minimum requirement. If the height is 120 cm or more, the program allows the user to ride.

  • The program begins by asking the user to input their height in centimeters, which is then stored in the height variable.
  • The program checks if the height is greater than or equal to 120 cm using the condition (height >= 120).
  • If the condition is true, it informs the user that they can ride the roller coaster by printing “You can ride the roller coaster!”
  • If the condition is false (i.e., the height is less than 120 cm), the program prints “Sorry, you cannot ride the roller coaster.”
  • The program thus determines eligibility for the ride based on the user’s height.
#include <iostream>
using namespace std;

int main() {
    int height;
    
    // Taking input from the user
    cout << "Enter your height (cm): ";
    cin >> height;
    
    // Decision-making based on height
    if (height >= 120) {
        cout << "You can ride the roller coaster!\n";
    } else {
        cout << "Sorry, you cannot ride the roller coaster.\n";
    }
    
    return 0;
}

Movie Rating Check

Movie Rating Checking In C++ using conditional statements
You want to watch a movie, but first, you need to check if you’re old enough. The minimum age requirement for the movie is 18 years. Write a program in C++ to check the eligibility.

Test Case:
Input: 20
Expected Output: You are old enough to watch this movie.

Explanation:

The program asks the user for their age. It then checks if the age is 18 or above using an if-else condition. If true, the program tells the user they can watch the movie. Otherwise, it informs them that they are too young.

  • The program starts by asking the user to enter their age, which is stored in the age variable.
  • It then evaluates if the age is 18 or older using the condition (age >= 18).
  • If the condition is true, the program outputs “You are old enough to watch this movie.”
  • If the condition is false (i.e., the age is less than 18), the program outputs “You are too young to watch this movie.”
  • This way, the program determines and communicates if the user meets the age requirement for watching the movie.
#include <iostream>
using namespace std;

int main() {
    int age;
    
    cout << "Enter your age: ";
    cin >> age;
    
    if (age >= 18) {
        cout << "You are old enough to watch this movie." << endl;
    } else {
        cout << "You are too young to watch this movie." << endl;
    }
    
    return 0;
}

Fitness App Rewards

Fitness app system in C+= using Conditional statements
You’re using a fitness app that rewards you if you log more than 1000 steps in a day. Write a program in C++ that takes the number of steps logged as input and tells you if you’ve earned a reward.

Test Case:
Input: 1200
Expected Output: “Congratulations! You’ve earned a reward!”

Explanation:

This program uses an if-else statement to determine if the number of logged steps exceeds 1000. If so, it informs the user that they’ve earned a reward. If the steps are 1000 or fewer, no reward is given.

  • The program begins by asking the user to enter the number of steps they’ve Jogged, which is stored in the steps variable.
  • It then checks if the number of steps is greater than 1000 using the condition (steps > 1000).
  • If the condition is true (i.e., the user logged more than 1000 steps), the program displays “Congratulations! You’ve earned a reward!”
  • If the condition is false (i.e., the user logged 1000 or fewer steps), the program displays “Keep trying for a reward.”
  • This approach helps the user know whether they have achieved the required number of steps to earn a reward.
#include <iostream>
using namespace std;

int main() {
    int steps; // Variable to store the number of steps logged

    // Prompting the user to enter the number of steps logged
    cout << "Enter the number of steps logged: ";
    cin >> steps;

    // Checking if the steps exceed 1000 to determine if a reward is earned
    if (steps > 1000) {
        cout << "Congratulations! You’ve earned a reward!\n";
    } else {
        cout << "Keep trying for a reward.\n";
    }

    return 0;
}

Syntax Scenarios Admin Login System

Scenario Based Question on If-else in C++
You are trying to log in to the admin portal of Syntax Scenarios, where editors manage articles, update content, and control important settings. Since this section contains sensitive information, only authorized users are allowed to enter.
Before access is granted, the system asks for two details:
A username
A password
The system carefully checks both values. If the entered username and password match the correct admin credentials, you are welcomed into the dashboard. However, even a small mistake in either field will result in access being denied.
If both username and password are correct, display: “Welcome to Syntax Scenarios Admin Portal”
Otherwise, display: “Access denied. Invalid credentials”

Write a C++ program that stores a predefined admin username and password, takes input from the user, and compares both values to display the appropriate message.

Test Case
Input:
Enter username: admin
Enter password: admin54321#

Expected Output: “Welcome to Syntax Scenarios Admin Portal”

Explanation:

  • The program starts by setting up the correct admin username and password. Think of these as the “key” to enter the admin portal.
  • Next, it asks the user to enter their username and password. These are compared with the stored correct credentials.
  • The program checks both the username and password together. Only if both are correct will the system grant access.
  • If either the username or password is wrong, the system will block access and show a warning message.
  • In short, it teaches how to use multiple conditions in decision-making to allow or block access in actual login systems.
#include <iostream>
#include <string>
using namespace std;

int main() {
    // Predefined admin credentials 
    string adminUsername = "admin";
    string adminPassword = "admin54321#";

    // Variables to store user input
    string enteredUsername, enteredPassword;

    // Prompt user to enter login details
    cout << "Enter username: ";
    cin >> enteredUsername;

    cout << "Enter password: ";
    cin >> enteredPassword;

    // Check if both username and password match
    if (enteredUsername == adminUsername && enteredPassword == adminPassword) {
        cout << "Welcome to Syntax Scenarios Admin Portal" << endl;
    } else {
        cout << "Access denied. Invalid credentials" << endl;
    }

    return 0;
}

Coffee Size Recommendation

Coffee Recommendation in C++ using Conditional Statements with if-else
You determine the appropriate coffee size based on the amount of coffee you consume. Write a C++ program that takes the volume of coffee in milliliters and recommends a coffee size. If the volume is more than 350 ml, recommend a “Large” size; if it’s between 200 ml and 350 ml, recommend a “Medium” size; and if it’s less than 200 ml, recommend a “Small” size.

Test Case:
Input: 220
Expected Output: “Medium”

Explanation:

The program reads the volume of coffee as input and utilizes if-else if-else statements to determine and print the suitable coffee size based on the provided volume because in this situation out of all conditons only one can be true.

  • The program starts by asking the user to input the coffee volume in milliliters, which is stored in the volume variable.
  • It then uses a series of if-else if-else statements to determine the appropriate coffee size based on the volume:
    • If the volume is greater than 350 ml, the program outputs “Large.”
    • If the volume is between 200 ml and 350 ml (inclusive), it outputs “Medium.”
    • If the volume is less than 200 ml, it outputs “Small.”
  • This helps the user decide on the coffee size based on the amount of coffee they have.
#include <iostream>
using namespace std;

int main() {
    double volume;
    
    // Asking the user to input the coffee volume
    cout << "Enter the coffee volume in milliliters (ml): ";
    cin >> volume;
    
    // Recommending the coffee size based on the volume
    if (volume > 350) {
        cout << "Large" << endl;
    } else if (volume >= 200) {
        cout << "Medium" << endl;
    } else {
        cout << "Small" << endl;
    }
    
    return 0;
}

Traffic Signal System

Scenario Based Question on If-else in C++
You are designing a traffic control system for a busy city intersection. Drivers must follow the traffic lights carefully to avoid accidents and maintain smooth traffic flow.
In this system:
"Red" light means Stop.
"Yellow" light means Wait and prepare to stop.
"Green" light means Go.
Sometimes, users may enter the wrong value, like "Blue" or "redlight". The program should be able to detect invalid signals and notify the user.

Write a C++ program that:
Prompts the user to enter the traffic signal color as a word (Red, Yellow, Green).
Displays the correct driver action based on the input.
Prints "Invalid signal" if the input is not one of the recognized colors.

Test Case
Input: Yellow
Expected Output: Wait

Explanation:

  • The program first asks the user to type the traffic signal color. It then checks the input one by one:
    • If it matches "Red", the program prints Stop.
    • If it matches "Yellow", it prints Wait.
    • If it matches "Green", it prints Go.
    • If the input doesn’t match any valid color, the program prints Invalid signal.
  • This way, the program ensures that it displays the correct action based on the traffic signal.
#include <iostream>
#include <string>
using namespace std;

int main() {
    string signal;

    // Prompt the user to enter the traffic signal color
    cout << "Enter traffic signal color (Red, Yellow, Green): ";
    cin >> signal;

    // Check the input and display the correct action
    if (signal == "Red" || signal == "red") {
        cout << "Stop" << endl;
    } 
    else if (signal == "Yellow" || signal == "yellow") {
        cout << "Wait" << endl;
    } 
    else if (signal == "Green" || signal == "green") {
        cout << "Go" << endl;
    } 
    else {
        cout << "Invalid signal" << endl;
    }

    return 0;
}

Store Discount Eligibility

Store Discount Eligibility using if-else in C++
 You’re shopping at a store that offers a discount if you spend $50 or more. Write a C++ program to check if the user is eligible for the discount based on their total purchase amount.

Test Case:
Input: 65.00
Expected Output: You are eligible for a discount!

Explanation:

The program will ask the user for the total purchase amount. Using an if-else condition, it checks if the amount is $50 or more. If true, it confirms that the user is eligible for a discount; otherwise, it informs them that they are not eligible.

  • The program begins by asking the user to input their total purchase amount, which is stored in the purchaseAmount variable.
  • It then uses an if-else condition to check if the total amount is $50 or more:
    • If the amount is $50 or more, the program outputs “You are eligible for a discount!”
    • If the amount is less than $50, the program outputs “You are not eligible for a discount.”
  • This helps the user determine if they qualify for a store discount based on their purchase amount.
#include <iostream>
using namespace std;

int main() {
    float purchaseAmount;
    
    cout << "Enter the total purchase amount: $";
    cin >> purchaseAmount;
    
    if (purchaseAmount >= 50) {
        cout << "You are eligible for a discount!" << endl;
    } else {
        cout << "You are not eligible for a discount." << endl;
    }
    
    return 0;
}

Bank Balance Alert

Banking Alert Using If-else condition in C++
You want to check your bank balance before making a purchase. If your balance is below $100, you receive an alert that your funds are low. Otherwise, you’re told that your balance is sufficient.

Test Case:
Input: 75.50
Expected Output: Alert! Your balance is low.

Explanation:

The program prompts the user for their bank balance. It uses an if-else condition to check if the balance is below $100. If true, it shows a low balance alert. Otherwise, it informs the user that their balance is sufficient.

  • The program starts by asking the user to input their bank balance, which is stored in the balance variable.
  • It then checks if the balance is less than $100 using an if-else condition:
    • If the balance is below $100, the program displays the alert message “Alert! Your balance is low.”
    • If the balance is $100 or more, the program informs the user that their balance is sufficient with the message “Your balance is sufficient.”
  • This helps the user understand whether they need to be cautious about their spending based on their current balance.
#include <iostream>
using namespace std;

int main() {
    float balance;
    
    cout << "Enter your bank balance: $";
    cin >> balance;
    
    if (balance < 100) {
        cout << "Alert! Your balance is low." << endl;
    } else {
        cout << "Your balance is sufficient." << endl;
    }
    
    return 0;
}

Rental Car Cost Calculator

Car Rent Calculator using Conditional Statements in C++ with if-else conditions
You need to determine the cost of renting a car based on the number of days rented:
For up to 3 days, the rate is $50 per day.
For 4 to 7 days, the rate is $40 per day for days 4 through 7.
For rentals longer than 7 days, the rate is $30 per day for the days beyond 7, with previous rates still applicable.
Write a program to calculate the total rental cost.

Test Case:
Input:
10 days
Expected Output: “Total rental cost: $410.00”

Explanation:

The program calculates the cost of renting a car based on the number of days rented, using different rates depending on the rental duration:

  • The program begins by asking the user for the number of days they rented the car, which is stored in the days variable.
  • It then calculates the total cost based on the rental duration using different rates:
    • For up to 3 days: The cost is calculated at $50 per day.
    • For days 4 through 7: The cost is $40 per day for these days.
    • For more than 7 days: The cost is $30 per day for the days beyond 7, with the previous rates applied to the initial days.
#include <iostream>
using namespace std;

int main() {
    int days;
    double cost = 0.0;
    
    // Prompt the user to enter the number of rental days
    cout << "Enter the number of days rented: ";
    cin >> days;
    
    // Calculate total rental cost based on days rented
    if (days <= 3) {
        cost = days * 50.0;
    } else if (days <= 7) {
        cost = 3 * 50.0 + (days - 3) * 40.0;
    } else {
        cost = 3 * 50.0 + 4 * 40.0 + (days - 7) * 30.0;
    }
    
    // Output the total rental cost
    cout << "Total rental cost: $" << cost << endl;
    
    return 0;
}

Utility Bill Calculator

utility Bill Calculator in C++ using if else conditional statements
You need to calculate the utility bill based on the total number of units consumed:

For up to 100 units, the charge is $0.50 per unit. For units between 101 and 200, the rate is $0.75 per unit for the units beyond the first 100. For units exceeding 200, the cost is $1.00 per unit for units above 200, while the previous rates still apply.
Write a program to compute the total utility bill based on these rates.

Test Case:
Input: 250 units
Expected Output: “Total utility bill: $215.00”

Explanation:

The program calculates the utility bill based on the number of units consumed. It uses if-else statements to apply different rates depending on the total units:

  • The program starts by asking the user for the number of units consumed, which is stored in the units variable.
  • It then calculates the total utility bill based on the number of units, using different rates for different ranges:
    • For up to 100 units: The bill is calculated at $0.50 per unit and the first if block will be executed.
    • For units between 101 and 200: The cost is $50 for the first 100 units plus $0.75 per unit for the additional units from 101 to 200. So, the else-if condition will be executed.
    • For units above 200: The cost includes $50 for the first 100 units, $75 for the next 100 units, plus $1.00 per unit for any units beyond 200. In this case the else block will execute because both the previous conditions were false.
#include <iostream>
using namespace std;

int main() {
    int units;
    double totalBill = 0.0;
    
    cout << "Enter the number of units consumed: ";
    cin >> units;
    
    if (units <= 100) {
        totalBill = units * 0.50;
    } else if (units <= 200) {
        totalBill = 100 * 0.50 + (units - 100) * 0.75;
    } else {
        totalBill = 100 * 0.50 + 100 * 0.75 + (units - 200) * 1.00;
    }
    
    cout << "Total utility bill: $" << totalBill << endl;
    
    return 0;
}

Emergency Hospital Priority System

Scenario Based Question on If-else in C++
In a busy hospital emergency room, doctors need to decide which patients should be treated first quickly. To help, a simple system is used to determine a patient’s priority level based on three important factors:
Heart rate (beats per minute)
Oxygen level (percentage in blood)
Age (years)
The system assigns priority according to these rules:
Critical: The patient’s heart rate is greater than 120, OR
The patient’s oxygen level is less than 90%
These patients need immediate medical attention.

High Priority: The patient’s age is above 60, AND
Heart rate is between 100 and 120 inclusive, AND
Oxygen level is 90% or above
These patients are at higher risk and should be attended quickly, but they are not immediately critical.

Normal: Any patient who does not meet the above conditions
These patients can be treated normally without urgency.

Write a C++ program that:
Takes input from the user for heart rate, oxygen level, and age.
Checks the patient’s condition step by step using if-else statements.
Displays the patient’s priority as "Critical", "High Priority", or "Normal".

Test Case
Input:
Input:
Heart rate: 130
Oxygen level: 95
Age: 45

Expected Output: Critical

Explanation

  • The program first asks the user to enter three pieces of information: heart rate, oxygen level, and age.
  • It validates each input to ensure it is a positive number. If not, it shows an error and stops.
  • Then, it checks if the patient is Critical.
    • If the heart rate is above 120 or oxygen level is below 90%, the patient is marked as Critical.
  • Else if the patient is not Critical, it checks for High Priority.
    • The patient is High Priority if they are older than 60 and their heart rate is in a safe range (100–120) and oxygen level is normal (90 or above).
  • Then, if neither Critical nor High Priority conditions are met, the patient is marked as Normal.
  • This way, the most urgent cases are handled first, and the program uses combined conditions (|| and &&) and ordered checks to decide correctly.
#include <iostream>
using namespace std;

int main() {
    int heartRate, oxygen, age;

    // Taking input from the user
    cout << "Enter heart rate (bpm): ";
    cin >> heartRate;
    if (heartRate <= 0) {
        cout << "Invalid input! Heart rate must be a positive number." << endl;
        return 0;
    }


    cout << "Enter oxygen level (%): ";
    cin >> oxygen;
    if (oxygen <= 0) {
        cout << "Invalid input! Oxygen level must be a positive number." << endl;
        return 0;
    }
   

    cout << "Enter age (years): ";
    cin >> age;
    if (age <= 0) {
        cout << "Invalid input! Age must be a positive number." << endl;
        return 0;
    }

    // Checking patient priority step by step
    if (heartRate > 120 || oxygen < 90) {
        // Critical condition
        cout << "Critical" << endl;
    } else if (age > 60 && heartRate >= 100 && heartRate <= 120 && oxygen >= 90) {
        // High priority condition
        cout << "High Priority" << endl;
    } else {
        // Normal condition
        cout << "Normal" << endl;
    }

    return 0;
}

Online Class Attendance

Scenario Based Question on If-else in C++
Imagine you are managing an online class platform. The class runs from 9:00 AM to 11:00 AM, and you want to automatically track students’ attendance based on the time they join.
The rules for attendance are:
If a student joins between 9:00 AM and 9:15 AM, they are on time, mark Present.
If a student joins after 9:15 AM but before 10:00 AM, they are slightly late, mark Late.
If a student joins 10:00 AM or later, or during PM hours, they are Absent.

You need to write a C++ program that:
Takes hour, minute, and AM/PM indicator separately from the user.
Determines Present, Late, or Absent based on the rules above.

Test Case
Input:
Hour: 9
Minute: 12
AM/PM: AM

Expected Output: Present

Explanation:

  • The program asks the student to enter the hour, minute, and whether it’s AM or PM separately.
  • The first check is whether the time is in the PM hours. If it is, the student is automatically marked Absent because the class only happens in the morning.
  • If it’s AM, the program then looks at the specific morning ranges to decide attendance:
    • If the student joins between 9:00 and 9:15 AM, they are Present.
    • If the student joins after 9:15 but before 10:00 AM, they are Late.
    • Any time from 10:00 AM onwards is considered Absent.
  • The order of checks matters: PM is checked first, then the exact hour and minute ranges.
  • By combining the hour and minute conditions logically, the program can accurately assign attendance.
#include <iostream>
using namespace std;

int main() {
    int hour, minute;
    char ampm;

    // Input hour, minute, and AM/PM separately
    cout << "Enter hour: ";
    cin >> hour;
    cout << "Enter minute: ";
    cin >> minute;
    cout << "Enter AM/PM (A/P): ";
    cin >> ampm;

    // Check PM first
    if (ampm == 'PM' || ampm == 'pM' || ampm == 'pm') {
        cout << "Absent" << endl;
    } 
    // Present: 9:00–9:15 AM
    else if (hour == 9 && minute <= 15) {
        cout << "Present" << endl;
    } 
    // Late: 9:16–9:59 AM
    else if (hour == 9 && minute > 15) {
        cout << "Late" << endl;
    } 
    // Any other time is absent
    else {
        cout << "Absent" << endl;
    }

    return 0;
}

Ethical Hacking Mission

Scenario Based Question on If-else in C++
You are an ethical hacker working for an intelligence agency. Your task is to retrieve sensitive files from a secured server as part of a cybersecurity audit.
During the security scan, the system has reported the following:
Operational Rules:
Some IPs are blacklisted due to prior suspicious activity: 10.0.0.5, 172.16.0.2, 192.168.1.50
Certain devices are authorized safe IPs: 192.168.0.101, 192.168.0.102

File access is controlled by following passcodes:
Intel2026 → Top-secret files
Intel2025 → Confidential files

Access Rules:
High Alert: If the IP is blacklisted → Access Denied
Safe Access: If the IP is safe AND passcode is correct → Access Granted (file type depends on passcode)
Failed Attempt: If IP is safe BUT passcode is wrong → Unauthorized Access Attempt
Unknown Device: If IP is neither blacklisted nor safe → Access Blocked for being unknown Device

Write a C++ program that takes the device IP and file passcode as input from the user and prints the correct access status.

Test Case
Input:
IP: 192.168.0.101
Passcode: Intel2026

Expected Output:
Access Granted: Top-secret Files Retrieved

Explanation:

  • The program first stores blacklisted IPs, safe IPs, and passcodes in separate variables. This is done so we can easily compare the user’s input with known values.
  • The user is asked to enter their device IP and file passcode. Reading input as strings allows us to check exact matches for IPs and passcodes.
  • Then the first check is whether the IP is blacklisted. This step is done first because blacklisted IPs are high-risk and must be denied immediately for security.
  • Next, the program checks if the IP is a safe authorized device. We do this after the blacklist check to only grant access to trusted devices. If the IP is safe, the program then checks the passcode:
    • If the passcode matches the top-secret code, access is granted for top-secret files. We do this to ensure only users with correct credentials get sensitive data.
    • If the passcode matches the confidential code, access is granted for confidential files. This allows users with lower-level access to still retrieve permitted data.
    • If the passcode is wrong, it is flagged as an unauthorized access attempt. This step helps log or alert for potential security breaches.
    • If the IP is neither blacklisted nor safe, the system blocks access and treats the device as unknown. This prevents unknown devices from entering the system.
  • Logical operators used:
    • || (OR) is used to check multiple IPs in one step. This reduces repeated checks and makes the code cleaner.
    • && (AND) is used to ensure both IP and passcode are correct before granting access. This prevents partial matches from granting access.
    • == is used to compare strings exactly because IPs and passcodes must match perfectly.
  • This setup uses a careful order of evaluation and combined conditions to handle all realistic scenarios.
#include <iostream>
#include <string>
using namespace std;

int main() {
    string ip, passcode;

    // Blacklisted IPs
    string blacklist1 = "10.0.0.5";
    string blacklist2 = "172.16.0.2";
    string blacklist3 = "192.168.1.50";

    // Safe IPs
    string safe1 = "192.168.0.101";
    string safe2 = "192.168.0.102";

    // Passcodes
    string topSecret = "Intel2026";
    string confidential = "Intel2025";

    cout << "Enter your device IP: ";
    cin >> ip;

    cout << "Enter file passcode: ";
    cin >> passcode;

    // Flat if-else checks
    if (ip == blacklist1 || ip == blacklist2 || ip == blacklist3) {
        cout << "Access Denied: Blacklisted IP";
    } 
    else if ((ip == safe1 || ip == safe2) && passcode == topSecret) {
        cout << "Access Granted: Top-secret Files Retrieved";
    } 
    else if ((ip == safe1 || ip == safe2) && passcode == confidential) {
        cout << "Access Granted: Confidential Files Retrieved";
    } 
    else if (ip == safe1 || ip == safe2) {
        cout << "Unauthorized Access Attempt";
    } 
    else {
        cout << "Access Blocked: Unknown Device";
    }

    return 0;
}

Speeding Ticket Calculator

Speeding ticket calculator in C++ using conditional statements
 You’re driving and want to avoid a speeding ticket. The speed limit is 60 km/h. If you drive within the speed limit, you’re safe. If you exceed the limit by up to 10 km/h, you get a warning. If you exceed it by more than 10 km/h, you receive a ticket. Write a C++ program to check the speed and assign a ticket for violating the conditions.

Test Case:
Input: 75
Expected Output: You are speeding! You will receive a ticket.

Explanation:

The program takes the user’s speed as input. It first checks if the speed is within the limit (60 km/h). If true, it tells the user they are safe. If false, it checks how much the limit is exceeded by. If the excess is 10 km/h or less, it issues a warning. If the excess is more than 10 km/h, it issues a ticket.

  • The program starts by asking the user to enter their driving speed, which is stored in the speed variable.
  • It then uses conditional checks to determine the appropriate response based on the speed:
    • If the speed is 60 km/h or less: The first if statememt will execute and program indicates that the user is driving safely.
    • If the speed is between 61 km/h and 70 km/h (exceeding the limit by up to 10 km/h): The second condition will execute and program issues a warning to slow down.
    • If the speed is more than 70 km/h (exceeding the limit by more than 10 km/h): The else block will execute and program notifies the user that they are speeding and will receive a ticket.
#include <iostream>
using namespace std;

int main() {
    int speed;
    
    cout << "Enter your driving speed (km/h): ";
    cin >> speed;
    
    if (speed <= 60) {
        cout << "You are driving safely." << endl;
    } else if (speed <= 70) {
        cout << "Warning! Slow down." << endl;
    } else {
        cout << "You are speeding! You will receive a ticket." << endl;
    }
    
    return 0;
}

To get a strong grip on if-else statements in C++, it is highly recommended to apply them to real-world scenarios. As the Syntax Scenario aims to teach coding creatively, by tackling these hands-on exercises, you not only sharpen your problem-solving skills but also gain confidence in writing efficient code.
Test your logic, experiment with inputs, and see the output instantly, all in our C/C++ Compiler!

Scroll to Top