Single line If condition without else clause [duplicate] - c#

This question already has answers here:
? operator without else-part
(3 answers)
Closed 3 years ago.
How can we write a single line If condition without else in the operator?
Example:
If(count==0) { count=2; }
How can we write above like below:
count=count==0?2;
As ternary operator requires if else condition. I want to do it without the ternery operator. Is there any operator available in C#?
Thanks.

You do not need to pair else with if; you can use it on its own:
if (count == 0)
count = 2;
This can be written in multiple ways if the syntax isn't to your liking:
if (count == 0) count = 2;
if (count == 0) { count = 2; }
if (count == 0) {
count = 2;
}
if (count == 0)
{
count = 2;
}
As another poster points out, you can use nullable int with initialization to null to have a binary interaction with the null coalescing operator:
int? count = null; // initialization
// ... later
count = count ?? 2;

count = count == 0 ? 2 : count;
Or for more fun:
using System;
public class Program
{
public static void Main()
{
foreach(int x in System.Linq.Enumerable.Range(-5, 10))
{
int count = x;
bool y = count == 0 && (0 == count++ - count++);
Console.WriteLine(count);
}
}
}

Related

how do i deal with c# left-hand side

i wanna ask something. My script gots some error
Here is it
using System;
namespace 3nplus1
{
class MainClass
{
public static void Main(string[] args)
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
while (Convert.ToBoolean(n = 1))
{
if (Convert.ToBoolean(n % 2 = 0))
{
n = n / 2;
Console.WriteLine(n);
}
else
{
n = 3*n + 1;
Console.WriteLine(n);
}
}
Console.WriteLine(n);
}
}
}
The error message says:"/Error CS0131: The left-hand side of an assignment must be a variable, property or indexer (CS0131) (3nplus1)
The error is located on the first "if" line
Please help.
Thanks and sorry for bad English.
You are confusing the = operator(assignment) with the == operator which is used for comparisons. So this is not a comparison that evaluates to true but an assignment(that returns the value that you assign).
if (Convert.ToBoolean(n % 2 = 0))
but the compiler complains about it because there must not be an expression on the left side of the assignment(like here) but a variable. You also don't need those Convert.ToBoolean.
Well, as said this is just a followup error. You want something like this:
Console.WriteLine("Enter a number(exit with q): ");
string input = Console.ReadLine();
while (!input.Equals("q", StringComparison.OrdinalIgnoreCase))
{
int n;
while (!int.TryParse(input, out n))
{
Console.WriteLine("Enter a valid integer");
input = Console.ReadLine();
}
int result = n % 2 == 0 ? n / 2 : 3 * n + 1;
Console.WriteLine(result);
input = Console.ReadLine();
}
change this part of your code
while (n != 1)
{
if (n % 2 == 0)
{
n = n / 2;
Console.WriteLine(n);
}
else
{
n = 3*n + 1;
Console.WriteLine(n);
}
}
A single = represents an assignment, however in your case you want to check for equality and therefore use the == operator. Doing this eliminates the need to use Convert.ToBoolean.
With an = you assign a value to a variable or a property. But you want to make a comparison on the equality and for that you take two ==.
And by the way you don't need Convert.ToBoolean. Just write:
if (n % 2 == 0)
{
...
}

Not all code paths return a value Error in tutorial [duplicate]

I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20, but I keep receiving the following error:
error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value
Here is my code:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
}
You're missing a return statement.
When the compiler looks at your code, it's sees a third path (the else you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value.
For my suggested fix, I put a return after your loop ends. The other obvious spot - adding an else that had a return value to the if-else-if - would break the for loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.
Instead of returning in the last iteration, just return true after the loop:
public static bool isTwenty(int num) {
for(int j = 1; j <= 20; j++) {
if(num % j != 0) {
return false;
}
}
return true;
}
Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.
I also experienced this problem and found the easy solution to be
public string ReturnValues()
{
string _var = ""; // Setting an innitial value
if (.....) // Looking at conditions
{
_var = "true"; // Re-assign the value of _var
}
return _var; // Return the value of var
}
This also works with other return types and gives the least amount of problems
The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.
I like to beat dead horses, but I just wanted to make an additional point:
First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).
My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:
bool result = false;
if(conditionA)
{
DoThings();
result = true;
}
else if(conditionB)
{
result = false;
}
else if(conditionC)
{
DoThings();
result = true;
}
return result;
So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.
Or simply do this stuff:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
else
{
return false;
}
}
}
Have a look at this one. It is the Ternary operator in C#.
bool BooleanValue = (num % 3 != 0) ? true : false;
This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.
Three alternatives together:
public bool test1()
{
int num = 21;
bool BooleanValue = (num % 3 != 0) ? true : false;
return BooleanValue;
}
public bool test2()
{
int num = 20;
bool test = (num % 3 != 0);
return test;
}
Even Shorter:
public bool test3()
{
int num = 20;
return (bool)(num % 3 != 0);
}
class Program
{
double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
double[] result;
public double[] CheckSorting()
{
for(int i = 1; i < a.Length; i++)
{
if (a[i] < a[i - 1])
result = b;
else
result = a;
}
return result;
}
static void Main(string[] args)
{
Program checkSorting = new Program();
checkSorting.CheckSorting();
Console.ReadLine();
}
}
This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true
This usually happens to me if I misplace a return statement, for example:
Adding a return statement, or in my case, moving it to correct scope will do the trick:
Not all code paths return a value.
Solution: To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.json file.

Return closest temperature to zero in C# language

I got asked the following question to program and below is the code I created. Is there a better way to do it? Thanks,
Implement the method ClosestToZero to return the temperature closer to zero which belongs to the array ts.
• If ts is empty, return 0 (zero)
• If two numbers are as close to zero, consider the positive integer as the closer to zero (eg. -5 and 5, return 5)
Input:
• Temperatures are always expressed with floating point numbers ranging from -273 to 5526
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
double[] ts = { 7, 12, -2, 8, 1 };
var result = closetozero(ts);
Console.WriteLine(result);
}
public static double closetozero(double[] ts)
{
int targetNumber = 0;
var nearest = ts.OrderBy(x => Math.Abs((long)x - targetNumber)).First();
return nearest;
}
}
}
Try this:
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
class Solution
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
string[] inputs = Console.ReadLine().Split(' ');
int closest=0;
if(n>0)
{
closest=int.Parse(inputs[0]);
for (int i = 1; i < n; i++)
{
int t = int.Parse(inputs[i]);
if(Math.Abs(closest-0)>Math.Abs(t-0))
{closest=t;}
else if(Math.Abs(closest-0) == Math.Abs(t-0))
{
if(closest-Math.Abs(closest)==0 && t-Math.Abs(t)==0)
{closest=closest;}
else if(closest-Math.Abs(closest)==0)
{closest=closest;}
else if(t-Math.Abs(t)==0)
{closest=t;}
}
}
}
Console.WriteLine(closest);
}
}
public static double ClosestToZero(double[] ts)
{
if(ts == null || ts.LongLength ==0 )
return 0;
double a = ts[0];
double b;
for(int i = 0; i <= ts.LongLength-1; i++){
if(Math.Abs(a) > Math.Abs(ts[i])){
a = ts[i];
}
else if(Math.Abs(a) == Math.Abs(ts[i]))
{
a = a > ts[i] ? a : Maths.Abs(ts[i]);
}
}
return a;
}
As Sweeper said, define "better".
In terms of runtime: Ditch the LINQ, write out the loop. The thing is your approach builds a list of values and then sorts them (O(n log n). A simple loop does no memory allocation and runs in O(n) time.
Also, it doesn't look to me like +5 is favored over -5 in your code, making it categorically wrong.
A "better" way would be to use ForEach and store the closest to zero as you go, taking +/- into consideration. There is no reason to sort the whole array.
Try this:
public static double closetozero(double[] ts)
{
return ts.Aggregate((t1, t0) => Math.Abs(t1) > Math.Abs(t0) ? t0 : t1);
}
public static int ComputeClosestToZero(int[] ts)
{
// Write your code here
// To debug: Console.Error.WriteLine("Debug messages...");
if (ts == null || ts.Length == 0)
return 0;
if (ts.Length == 1)
return ts[0];
if (ts.Length == 2 )
return ts[0]>=ts[1] ? ts[0] :ts[1];
int a = ts[0];
bool b = false;
for (int i = 1; i <= ts.Length - 1; i++)
{
if (ts[i] > 0 && a > 0)
{
b = true;
if (ts[i] == 1)
return ts[i];
if (a > ts[i])
{
a = ts[i];
}
}
else if(!b)
{
if (ts[i] == -1)
return ts[i];
if (a < ts[i])
{
a = ts[i];
}
}
}
return a;
}
public static double ClosestToZero(double[] ts)
{
if(ts == null || ts.LongLength ==0 )
return 0;
double a = ts[0];
double b;
for(int i = 0; i <= ts.LongLength-1; i++){
if(Math.Abs(a) > Math.Abs(ts[i])){
a = ts[i];
}
else if(Math.Abs(a) == Math.Abs(ts[i]))
{
a = a > ts[i] ? a : ts[i];
}
}
return a;
}

not all code path return value? [duplicate]

I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20, but I keep receiving the following error:
error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value
Here is my code:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
}
You're missing a return statement.
When the compiler looks at your code, it's sees a third path (the else you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value.
For my suggested fix, I put a return after your loop ends. The other obvious spot - adding an else that had a return value to the if-else-if - would break the for loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.
Instead of returning in the last iteration, just return true after the loop:
public static bool isTwenty(int num) {
for(int j = 1; j <= 20; j++) {
if(num % j != 0) {
return false;
}
}
return true;
}
Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.
I also experienced this problem and found the easy solution to be
public string ReturnValues()
{
string _var = ""; // Setting an innitial value
if (.....) // Looking at conditions
{
_var = "true"; // Re-assign the value of _var
}
return _var; // Return the value of var
}
This also works with other return types and gives the least amount of problems
The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.
I like to beat dead horses, but I just wanted to make an additional point:
First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).
My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:
bool result = false;
if(conditionA)
{
DoThings();
result = true;
}
else if(conditionB)
{
result = false;
}
else if(conditionC)
{
DoThings();
result = true;
}
return result;
So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.
Or simply do this stuff:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
else
{
return false;
}
}
}
Have a look at this one. It is the Ternary operator in C#.
bool BooleanValue = (num % 3 != 0) ? true : false;
This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.
Three alternatives together:
public bool test1()
{
int num = 21;
bool BooleanValue = (num % 3 != 0) ? true : false;
return BooleanValue;
}
public bool test2()
{
int num = 20;
bool test = (num % 3 != 0);
return test;
}
Even Shorter:
public bool test3()
{
int num = 20;
return (bool)(num % 3 != 0);
}
class Program
{
double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
double[] result;
public double[] CheckSorting()
{
for(int i = 1; i < a.Length; i++)
{
if (a[i] < a[i - 1])
result = b;
else
result = a;
}
return result;
}
static void Main(string[] args)
{
Program checkSorting = new Program();
checkSorting.CheckSorting();
Console.ReadLine();
}
}
This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true
This usually happens to me if I misplace a return statement, for example:
Adding a return statement, or in my case, moving it to correct scope will do the trick:
Not all code paths return a value.
Solution: To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.json file.

C# compiler error: "not all code paths return a value"

I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20, but I keep receiving the following error:
error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value
Here is my code:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
}
You're missing a return statement.
When the compiler looks at your code, it's sees a third path (the else you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value.
For my suggested fix, I put a return after your loop ends. The other obvious spot - adding an else that had a return value to the if-else-if - would break the for loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.
Instead of returning in the last iteration, just return true after the loop:
public static bool isTwenty(int num) {
for(int j = 1; j <= 20; j++) {
if(num % j != 0) {
return false;
}
}
return true;
}
Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.
I also experienced this problem and found the easy solution to be
public string ReturnValues()
{
string _var = ""; // Setting an innitial value
if (.....) // Looking at conditions
{
_var = "true"; // Re-assign the value of _var
}
return _var; // Return the value of var
}
This also works with other return types and gives the least amount of problems
The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.
I like to beat dead horses, but I just wanted to make an additional point:
First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).
My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:
bool result = false;
if(conditionA)
{
DoThings();
result = true;
}
else if(conditionB)
{
result = false;
}
else if(conditionC)
{
DoThings();
result = true;
}
return result;
So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.
Or simply do this stuff:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
else
{
return false;
}
}
}
Have a look at this one. It is the Ternary operator in C#.
bool BooleanValue = (num % 3 != 0) ? true : false;
This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.
Three alternatives together:
public bool test1()
{
int num = 21;
bool BooleanValue = (num % 3 != 0) ? true : false;
return BooleanValue;
}
public bool test2()
{
int num = 20;
bool test = (num % 3 != 0);
return test;
}
Even Shorter:
public bool test3()
{
int num = 20;
return (bool)(num % 3 != 0);
}
class Program
{
double[] a = new double[] { 1, 3, 4, 8, 21, 38 };
double[] b = new double[] { 1, 7, 19, 3, 2, 24 };
double[] result;
public double[] CheckSorting()
{
for(int i = 1; i < a.Length; i++)
{
if (a[i] < a[i - 1])
result = b;
else
result = a;
}
return result;
}
static void Main(string[] args)
{
Program checkSorting = new Program();
checkSorting.CheckSorting();
Console.ReadLine();
}
}
This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true
This usually happens to me if I misplace a return statement, for example:
Adding a return statement, or in my case, moving it to correct scope will do the trick:
Not all code paths return a value.
Solution: To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.json file.

Categories

Resources