20/06/2013

If you want to toggle a value from 1 to 0 or 0 to 1 depending on the current value then you are at the right place.

(i.e. change the value to 0 only if it’s 1 now and change it to 1 only if it is 0 at the moment)

You can use this to toggle between true and false as well.

Problem: Convert the value to zero if it’s one or convert the value to one if it’s zero.

Solution:

Use this formula : New Value = (Old value -1) * -1

e.g. zero = (one – 1) * -1;

e.g. one = (zero – 1) * -1;

Example:

private void myCode()
{
int x;
/ * --- case 1: value of x is one. The expected result after applying the formula is 0 --- */
x = 1;
printX(x); // prints Value of X is : 1
// apply
x = toggleOneZero(x);
//Check the output
printX(x); // prints Value of X is : 0
/ * --- case 2: value of x is zero. The expected result after applying the formula is 1 --- */
x = 0;
printX(x); // prints Value of X is : 0
// apply
x = toggleOneZero(x);
//Check the output
printX(x); // prints Value of X is : 1
}
private int toggleOneZero(int originalValue)
{
int newValue = (originalValue -1) * -1
return newValue;
}
private void printX(int x)
{
Console.WriteLine("Value of X is :" + x.ToString());
}

Menol

ILT

### Like this:

Like Loading...

*Related*