Let’s consider a scenario where we want to categorize a person as a “Child,” “Teenager,” “Adult,” or “Senior” based on their age. Additionally, we will have a special condition that if the person is a teenager and a student, they will be categorized as a “Student Teenager.”
#include <iostream>
#include <string>
// Function to categorize a person based on age and student status
std::string categorizePerson(int age, bool isStudent) {
return (age < 13) ? "Child" :
(age >= 13 && age <= 19) ? (isStudent ? "Student Teenager" : "Teenager") :
(age >= 20 && age <= 64) ? "Adult" :
"Senior";
}
int main() {
int age1 = 10;
bool isStudent1 = false;
int age2 = 16;
bool isStudent2 = true;
int age3 = 25;
bool isStudent3 = false;
int age4 = 70;
bool isStudent4 = false;
std::cout << "Age " << age1 << ": " << categorizePerson(age1, isStudent1) << std::endl;
std::cout << "Age " << age2 << ": " << categorizePerson(age2, isStudent2) << std::endl;
std::cout << "Age " << age3 << ": " << categorizePerson(age3, isStudent3) << std::endl;
std::cout << "Age " << age4 << ": " << categorizePerson(age4, isStudent4) << std::endl;
return 0;
}
When you run this code, you will get the following output:
Age 10: Child
Age 16: Student Teenager
Age 25: Adult
Age 70: Senior
categorizePerson
: This function takes two parameters: age
and isStudent
. It uses nested ternary operators to determine the category based on the age and student status.age
is less than 13, the category is “Child.”age
is between 13 and 19 (inclusive), the category depends on whether the person is a student:isStudent
is true, the category is “Student Teenager.”age
is between 20 and 64 (inclusive), the category is “Adult.”age
is 65 or older, the category is “Senior.”main
function demonstrates how the categorizePerson
function can be used with different ages and student statuses. It prints the category for each example.if-else
statements for better readability.