C# Programming - Control Instructions - Discussion

Discussion Forum : Control Instructions - General Questions (Q.No. 9)
9.
Which of the following code snippets are the correct way to determine whether a is Odd or Even?
  1. int a;
    String res; 
    if (a % 2 == 0)
        res = "Even"; 
    else 
        res = "Odd";
  2. int a; 
    String res; 
    if (a Mod 2 == 0) 
        res = "Even"; 
    else
        res = "Odd";
  3. int a;
    Console.WriteLine(a Mod 2 == 0 ? "Even": "Odd");
  4. int a; 
    String res;
    a % 2 == 0 ? res = "Even" : res = "Odd";
    Console.WriteLine(res);
1, 3
1 Only
2, 3
4 Only
None of these
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
10 comments Page 1 of 1.

Dudie said:   8 years ago
4 is incorrect for 2 reasons:

(a) ternary operator cannot execute statements, only returns a value based on the condition
(b) ternary operator cannot be used as a statement.

3 would be correct if it was :
Console.WriteLine(a % 2 == 0 ? "Even": "Odd");
(1)

Sunil Reddy Kamini said:   6 years ago
There are no Mod exits in C# so can exclude 2, 3 snippets
Ternary operator cannot be in such an ugly manner being a programmer in 4th Snippet.

Assuming that a's value is read as an input from the user the snippet1 becomes valid otherwise None of These.

Gopesh said:   1 decade ago
@Mahdi.

They are saying that what is the correct way to determine that a value is even or odd, they are not saying that find there is an error or not.

Mahdi said:   1 decade ago
In this snipped code, it is necessary to initial a variable, otherwise we have compiler error
So with this condition, E in correct

HHH said:   1 decade ago
@Nidhin int a = 2;

string res;

res= a % 2 == 0 ? "True" : "False";

Console.WriteLine(res);

Nidhin said:   1 decade ago
4 will be correct if it is as,

a % 2 == 0 ? (res = "Even") :( res = "Odd");

Basma said:   1 decade ago
res = ( a % 2) == 0 ? ("Even") : "Odd";

But what is about mod?

Urim said:   7 years ago
Both (1) and (4) will result in error use of un-assigned variables.

Csharp said:   1 decade ago
@Nidhin What difference does it make, why is the 4th incorrect.

Arjun said:   9 years ago
Unassigned local variable 'a'.

Post your comments here:

Your comments will be displayed after verification.