Search

Entry Ticket Discount [Conditionals] (C++)

Part 3 of the C++ Course

Introduction

Writing the program

The "Else" clause

Resolving a problem

What's Next?

Introduction
Writing the program
The "Else" clause
Resolving a problem
What's Next?

In this article, we’ll create a program in the language that prompts the user for their age and then informs them about the cost of an “entry ticket” as well as any applicable discounts based on their age. We’ll explore conditionals as we build this program.

First, we’ll declare an int variable named “age” to store the user’s input. Then, we’ll use cin to prompt the user for their age.

int age;
cin >> age;

Next, we’ll utilize the if statement to check if the age is less than or equal to 12. If so, we’ll print a message to inform the user that they are eligible for a free pass.

if ​(age <= 12) {
  cout << "$0 - You get a free pass!" << endl;  
}
#include <iostream>

using namespace std;

int main() {
    int a = 2;
    int b = 1;
    if (a == b) {
        cout << "a and b are equal" << endl;
    }
    cout << "a - b = " << a - b << endl;
}

a and b are equal

a – b = 1

a and b are equal
a – b = 1

a – b = 0

Correct

As a and b are not equal the if statement won’t be executed. However the line printing the difference between a and b (a.k.a a - b) will run as it has nothing to do with the if statement.

We can also add another if statement to determine whether or not the user is more than 12 years old, and if so, print that they have to pay $12.

if (age > 12) {
  cout << "$12" << endl;
}

Let’s print a special and different message for people who are exactly 12 years old. Looking at our current program, we’ve handled users who are 12 or younger with one if statement and those older than 12 with a separate condition. To specifically address the case of 12-year-old users, we can remove the equal sign from the first condition (only checking if age is less than 12), which results in our program to not account for 12-year-olds. Then, add another statement to handle this case specifically.

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age < 12) {
        cout << "$0 - You get a free pass!" << endl;
    }

    if (age > 12) {
        cout << "$12" << endl;
    }

    if (age == 12) {
        cout << "$0 - Take advantage of these last free passes" << endl;
    }
}

This program grants individuals under 12 a free pass. For 12-year-olds, it provides a message stating they get a free pass and they have to take advantage of these final free passes! Older users are charged the full price.

Notice that in the third if statement, two equal signs (==) are used instead of a single one (=). This is because the single equal sign is reserved for assignments. For example, when you write:

int age = 19;
age = 20;

you use the single equal sign operator = to assign a value to the variable age. Therefore, the double equal sign operator == was created for comparison. It checks if the value on the left-hand side is equal to the value on the right-hand side.

Let’s review the first code that we wrote in this article.

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age <= 12) {
        cout << "0$ - You get a free pass!" << endl;
    }
    if (age > 12) {
        cout << "12$" << endl;
    }
}

It’s evident that the second if statement is essentially the opposite of the first one (“age is greater than 12” is the exact opposite of “age is less than or equal to 12”). In situations like this, the else clause can be employed in lieu of the second if statement.

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age <= 12) {
        cout << "0$ - You get a free pass!" << endl;
    } else {
        cout << "12$" << endl;
    }
}

So, initially, our program checks if the user is 12 or younger. If they are, a free pass is granted. Otherwise, the full price is printed.

If we run our program now, we’ll observe the following behavior:
10-year-old user:

0$ - You get a free pass!

12-year-old user:

0$ - You get a free pass!

12-year-old user:

0$ - You get a free pass!

20-year-old user:

12$

a malicious user who claims to be -100 years old!

0$ - You get a free pass!

Let’s say the user claims to be -100 years old! Our program still happily offers them a free pass. We clearly need to address this loophole in our program’s logic.

One solution could involve using unsigned variables, which essentially only accept positive numbers and can’t hold negative ones.

#include <iostream>

using namespace std;

int main() {
    unsigned int age;
    cin >> age;
    if (age <= 12) {
        cout << "0$ - You get a free pass!" << endl;
    } else {
        cout << "12$" << endl;
    }
}

All the numerical data types mentioned in the previous article, such as int, have both signed and unsigned variants. However, a drawback of using unsigned variables is that when a negative number is assigned to them, it turns into a very large positive number. We’ll delve into why this occurs later in this series, but for now, it does provide a solution to our issue because any resulting large number will inevitably be greater than 12, allowing our program to (almost) function correctly. Nevertheless, this approach prevents us from informing the user about their incorrect input and introduces several edge cases. (we’ll talk about them later on in this series!)

A better solution would involve checking for “incorrect” inputs and “sanitizing” the input. To achieve this, we can add another if statement to verify whether the age is negative (i.e., smaller than 0) and print an error message stating that “Age has to be a positive number.”

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age < 0) {
        cout << "Age has to be a positive number" << endl;
    }
    if (age <= 12) {
        cout << "0$ - You get a free pass!" << endl;
    } else {
        cout << "12$" << endl;
    }
}

But the problem this program is that both the if statements’ bodies execute if a negative number is fed into our program, resulting in unexpected output:

-100
Age has to be a positive number‍
0$ - You get a free pass!

To address this issue, we can move the second if-else statement inside the else clause of the first if statement. This way, our program will follow these steps: first, it will check if the age is negative and print an error message if it is. If the age is not negative, it will proceed to check whether it is less than or equal to 12, granting the user a free pass if it is. Otherwise, it will print the full price.

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age < 0) {
        cout << "Age has to be a positive number" << endl;
    } else {
	    if (age <= 12) {
	        cout << "0$ - You get a free pass!" << endl;
	    } else {
	        cout << "12$" << endl;
	    }
    }
}
-100
Age has to be a positive number‍

This code functions perfectly fine. However, employing multiple nested if/else statements can lead to what’s known as spaghetti code 🍝, making your code difficult to read and maintain. To address this issue, a syntax called else if has been created. It essentially is an equivalent to what we just wrote, an if statement placed within an else clause.

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age < 0) {
        cout << "Age has to be a positive number" << endl;
    } else if (age <= 12) {
		cout << "0$ - You get a free pass!" << endl;
	} else {
		cout << "12$" << endl;
	}
}

When this program is executed, it basically performs the same tasks as our previous code. It prints an error message if the age variable is negative. Otherwise, if the age is below or equal to 12, it grants the free pass. If none of these conditions are met, it prints the full price.

Logically, there can only be one if or else clause in each of these chains. However else if statements have no limitation in count and you can add as many as needed:


#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age < 0) {
        cout << "Age has to be a positive number" << endl;
    } else if (age <= 12) {
		cout << "0$ - You get a free pass!" << endl;
	} else if (age <= 18) {
	    cout << "6$ - You get 50% discount" << endl;
	} else {
		cout << "12$" << endl;
	}
}

This program first ensures that the age is not negative. If the user is 12 or younger, it provides a free pass. If the user is older than 12 but 18 or younger, it grants a 50% discount. If none of these conditions are met (meaning the user is more than 18 years old), the full price is printed.

This post delved into the use of conditionals and if/else if/else statements in the :langs_cpp: language. We explored these concepts by developing a program that determines a user’s eligibility for a discounted ticket based on their age.

#include <iostream>

using namespace std;

int main() {
    int age;
    cin >> age;
    if (age < 0) {
        cout << "Age has to be a positive number" << endl;
    } else if (age <= 12) {
		cout << "0$ - You get a free pass!" << endl;
	} else if (age <= 18) {
	    cout << "6$ - You get 50% discount" << endl;
	} else {
		cout << "12$" << endl;
	}
}
-100
Age has to be a positive number‍
5
0$ - You get a free pass!
13
6$ - You get 50% discount
33
12$

Log in to save your progress.

With an account, you can mark the projects you finish as completed and save your progress.

Leave a Reply

Next step

Step1

This website relies on cookies to ensure you get the best experience