Hi I was writing a basic program to find if the input number is prime or not. I have a checkPrime(num)
function that checks for prime number and returns true
if num is prime else returns false
. Now in my main()
function I used conditional operator to shorten the code but I am getting an error which I am not sure about. Below is my code :
static void Main(String[] args) {
int n = Int32.Parse(Console.ReadLine());
while (n-- > 0) {
int num = Int32.Parse(Console.ReadLine());
(checkPrime(num) == true) ? Console.WriteLine("Prime") : Console.WriteLine("Not Prime");
}
}
When I compile, I get the error as Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
in my while loop at conditional statement line. I am not sure what is it that I am missing. There is similar question here and people have answered that the conditional operator line is an expression and not a statement so there has to be some sort or assignment for the value of the expression. Same kind of example is given in MSDN reference where the explanation does something like this
// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";
But what I am not able to understand is in my function all I am trying to do is check the return value of the function and then print the output. So where does this expression thing comes in my case.