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?
int a; String res; if (a % 2 == 0) res = "Even"; else res = "Odd";
int a; String res; if (a Mod 2 == 0) res = "Even"; else res = "Odd";
int a; Console.WriteLine(a Mod 2 == 0 ? "Even": "Odd");
int a; String res; a % 2 == 0 ? res = "Even" : res = "Odd"; Console.WriteLine(res);
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");
(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)
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
So with this condition, E in correct
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.
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.
Nidhin said:
1 decade ago
4 will be correct if it is as,
a % 2 == 0 ? (res = "Even") :( res = "Odd");
a % 2 == 0 ? (res = "Even") :( res = "Odd");
Basma said:
1 decade ago
res = ( a % 2) == 0 ? ("Even") : "Odd";
But what is about mod?
But what is about mod?
Csharp said:
1 decade ago
@Nidhin What difference does it make, why is the 4th incorrect.
HHH said:
1 decade ago
@Nidhin int a = 2;
string res;
res= a % 2 == 0 ? "True" : "False";
Console.WriteLine(res);
string res;
res= a % 2 == 0 ? "True" : "False";
Console.WriteLine(res);
Arjun said:
9 years ago
Unassigned local variable 'a'.
Urim said:
7 years ago
Both (1) and (4) will result in error use of un-assigned variables.
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.
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.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers