C#.NET — Initialize two variables i and j to 10 each: which statements are valid?

Difficulty: Easy

Correct Answer: 1, 3

Explanation:


Introduction / Context:
The exercise assesses valid C# initialization forms when you want both variables i and j to be set to 10.



Given Data / Assumptions:

  • (1) int i = 10; int j = 10;
  • (2) int i, j; i = 10 : j = 10;
  • (3) int i = 10, j = 10;
  • (4) int i, j = 10;
  • (5) int i = j = 10;


Concept / Approach:
Legal, clear initializations are either two separate statements or a compound declaration assigning both. The colon operator in (2) is invalid in this context. In (4) only j is initialized. In (5) chained assignment requires j to already exist in scope.



Step-by-Step Solution:

(1) Valid: both i and j become 10. (2) Invalid: uses ":" which is not assignment. (3) Valid: both initialized in one statement. (4) Not meeting the requirement: i is uninitialized. (5) Invalid in a declaration: j is not declared before use.


Verification / Alternative check:
Compile examples (1) and (3) — both succeed; (2), (4), (5) either fail or don’t meet the “both 10” requirement.



Why Other Options Are Wrong:
They include invalid constructs or statements that fail to set both variables to 10.



Common Pitfalls:
Believing chained assignment works inside the same declaration for multiple new identifiers.



Final Answer:
1, 3

More Questions from Datatypes

Discussion & Comments

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