C++ Code Example: Categorizing a Person Based on Age and Other Conditions

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.”

Code Example

#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;
}

Output

When you run this code, you will get the following output:

Age 10: Child
Age 16: Student Teenager
Age 25: Adult
Age 70: Senior

Code Explanation

  1. Function 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.
  2. Nested Ternary Operators: The ternary operators are nested to handle multiple conditions:
    • If age is less than 13, the category is “Child.”
    • If age is between 13 and 19 (inclusive), the category depends on whether the person is a student:
      • If isStudent is true, the category is “Student Teenager.”
      • Otherwise, the category is “Teenager.”
    • If age is between 20 and 64 (inclusive), the category is “Adult.”
    • If age is 65 or older, the category is “Senior.”
  3. Main Function: The main function demonstrates how the categorizePerson function can be used with different ages and student statuses. It prints the category for each example.

Key Points

  • Readability: While this example is more complex, it still remains relatively readable because the conditions are straightforward. However, for even more complex scenarios, consider using if-else statements for better readability.
  • Ternary Operator Use: The nested ternary operators allow us to handle multiple conditions concisely within a single return statement.
  • Special Conditions: The example includes a special condition for “Student Teenager,” showing how additional logic can be incorporated into the ternary structure.