YouTip LogoYouTip

C Exercise Example15

## C Programming Exercise - Example 15: Nested Conditional Operators This tutorial is part of the classic C programming practice series. In this exercise, we will learn how to use nested conditional (ternary) operators to evaluate and categorize student grades based on their scores. --- ### Problem Description Write a C program that uses **nested conditional operators** to classify student scores into grades: * Scores **$\ge$ 90** are represented by **'A'**. * Scores between **60 and 89** (inclusive) are represented by **'B'**. * Scores **below 60** are represented by **'C'**. --- ### Technical Concept: The Conditional Operator (`? :`) The conditional operator, also known as the ternary operator, is the only operator in C that takes three operands. It is a shorthand way of writing an `if-else` statement. #### Syntax ```c condition ? expression_if_true : expression_if_false; ``` #### Nested Conditional Operators To handle multiple conditions (similar to an `if-else if-else` chain), you can nest conditional operators inside one another: ```c condition1 ? value1 : (condition2 ? value2 : value3); ``` In this exercise, we will nest a second ternary operator inside the "false" branch of the first one to evaluate the three grade ranges. --- ### Source Code Implementation Below is the complete, compilable C program. The comments have been translated into English for clarity. ```c #include int main() { int score; char grade; // Prompt the user to input the score printf("Please enter the score: "); if (scanf("%d", &score) != 1) { printf("Invalid input.\n"); return 1; } // Determine the grade using nested conditional operators grade = (score >= 90) ? 'A' : ((score >= 60) ? 'B' : 'C'); // Output the resulting grade printf("Grade: %c\n", grade); return 0; } ``` --- ### Sample Output #### Test Case 1: Score in the 'B' range ```text Please enter the score: 87 Grade: B ``` #### Test Case 2: Score in the 'A' range ```text Please enter the score: 95 Grade: A ``` #### Test Case 3: Score in the 'C' range ```text Please enter the score: 52 Grade: C ``` --- ### Code Analysis & Considerations 1. **Operator Precedence and Parentheses**: In the expression `(score >= 90) ? 'A' : ((score >= 60) ? 'B' : 'C')`, the outer parentheses around the nested ternary expression `((score >= 60) ? 'B' : 'C')` are optional because the conditional operator associates from right to left. However, keeping them explicitly written makes the code significantly more readable and prevents logical errors. 2. **Readability vs. Conciseness**: While nested ternary operators make the code compact, nesting them too deeply (e.g., more than 3 levels) can make the code difficult to read and maintain. For complex multi-branch logic, standard `if-else if-else` statements or `switch` statements are generally preferred in production environments.
← C Exercise Example16C Exercise Example14 β†’