C conditional (?:) with character ranges: what does this program print? #include<stdio.h> int main() { char ch; ch = 'A'; printf("The letter is"); printf("%c", ch >= 'A' && ch <= 'Z' ? ch + 'a' - 'A' : ch); printf("Now the letter is"); printf("%c ", ch >= 'A' && ch <= 'Z' ? ch : ch + 'a' - 'A'); return 0; }

Difficulty: Medium

Correct Answer: The letter is a Now the letter is A

Explanation:


Introduction / Context:
This snippet uses the conditional operator to convert case based on whether a character lies between 'A' and 'Z'. It also demonstrates that the variable ch itself is never modified; only expressions are computed and printed. Understanding expression evaluation without assignment is key here.


Given Data / Assumptions:

  • ch is initialized to 'A'.
  • Expressions ch + 'a' - 'A' compute the lowercase equivalent when ch is uppercase ASCII.
  • No assignment to ch occurs after initialization.


Concept / Approach:
The first printf prints a lowercase version if ch is uppercase; the second prints the original uppercase when the condition is true because it returns ch unchanged in that branch. Concatenated literals “The letter is” and “Now the letter is” have no trailing spaces, so outputs abut directly with the converted letters.


Step-by-Step Solution:

Initial ch = 'A', condition ch between 'A' and 'Z' is true.First conditional prints ch + 'a' - 'A' → 'a'.Second conditional prints ch because the uppercase condition is true → 'A'.Overall text: “The letter is” then 'a', then “Now the letter is” then 'A'.


Verification / Alternative check:
Insert explicit spaces in the format strings to see layout changes; logic of the character values remains the same.


Why Other Options Are Wrong:

Option b swaps cases and misreads the second conditional.“Error” is wrong; code is valid C.“None of above” is invalid because option a matches exactly.


Common Pitfalls:
Assuming ch changes value across prints; misunderstanding that only expressions change, not the variable itself.


Final Answer:
The letter is a Now the letter is A.

More Questions from Expressions

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion