4

Simple question really, although I'm not sure if there's an answer. I am handling an integer which can be positive or negative.

However, I would like to either increment or decrement it dependant on the sign.

For example, if it's "2", then add 1 and make it "3".

If it's "-2", then subtract 1 and make it "-3".

I already know the obvious method to fix this by adding if statements and having two separate increment and decrement sections. But, I'm trying to limit the amount of code I use and would like to know if there's a similar way of doing this from a built-in function or procedure.

Shivam Malhotra
  • 309
  • 1
  • 3
  • 10

5 Answers5

8

Try it:

int IncOrDec(int arg)
{
    return arg >= 0 ? ++arg : --arg;
}
DreamChild
  • 411
  • 2
  • 3
6

You can use built-in Math.Sign for this:

int a = 1;
int b = a + Math.Sign(a); // b == 2

int c = -1;
int d = c + Math.Sign(c); // d == -2

Or even shorter version, suggested in comments:

int a = 1;
a += Math.Sign(a); // a == 2

int c = -1;
c += Math.Sign(c); // c == -2
Andrei
  • 55,890
  • 9
  • 87
  • 108
  • 2
    Note that this could be reduced to "a += Math.Sign(a);", which is both shorter than other solutions and still readable. This is therefore probably the best option. – Chris Jun 25 '13 at 12:13
  • @Chris, true, although actually it depends on whether you need to inc|dec the same variable. – Andrei Jun 25 '13 at 12:14
  • Yep, but since the questioner actually explicitly said they need to incr/decr the variable, that seems a pretty safe bet here. – Chris Jun 25 '13 at 12:16
3

Simply use ternary operator like this:-

num >= 0 ? ++num : --num;
Vivek Sadh
  • 4,230
  • 3
  • 32
  • 49
1

If you do not wish to clutter your code you can use Ternary Operators;

int number = (original > 0) ? original + 1 : original - 1;
Sander
  • 1,264
  • 1
  • 16
  • 26
0
using System;

namespace posneg
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = Int32.Parse(args[0]);

            Console.WriteLine(( num + ( num / Math.Abs(num) )));

        }
    }
}
Kevin Pluck
  • 641
  • 5
  • 14
  • Just need to make sure to indent all code bocks (there's a little "code" button in the text editor to help with that) – Chris Sinclair Jun 25 '13 at 12:09
  • As an explanation. Math.Abs() gives the positive value of any integer. Dividing an integer by itself will always give 1 (including if they are both negative). So dividing a negative integer by it's positive value will give -1, the same math will give +1 if the integer is positive. No conditionals involved. – Kevin Pluck Jun 25 '13 at 12:16
  • @ShivamMalhotra I know you've got a good answer there but I'm sure you'd be interested in this one :-) – Kevin Pluck Jun 25 '13 at 16:02
  • 1
    It wasn't explicitly outlined in the question, but what if `num` is zero? – DanM7 Feb 06 '14 at 20:20
  • Then it goes boom! :-) (bother) – Kevin Pluck Feb 08 '14 at 21:36