I'm trying to write the function:

int sum(int x, int y)

For this function, I need to return sum of m and n using only increment, decrement and unary -. m and n can be any integers e.g. if m is 4 and n is -5, the return value would be -1

I need to handle the cases where m and/or n is negative. Make use of the properties: m + n = -(-m + -n) and m + n = n + m.

So if the sum is -5 + -4 that can be evaluated as -(5 + 4). Also 5 + -4 can be evaluated at -4 + 5.

When the second parameter is positive use the rule a + b = (a + (b-1)) + 1.

The one and only base case is when the second parameter is zero.

Here is my solution:

int sum(int x, int y)
{
    if(y == 0)
    {
        return x;
    }
    if(x < 0 && y < 0) 
    {
        return -(sum(++x,++y));
    }
    if(x < 0)
    {
        return sum(++x,--y);
    }
    if(y < 0)
    {
        return sum(--x,++y);
    }
    if(y > 0)
    {
        return sum(++x,y-1);
    }
    return sum(++x,++y);
}

int main()
{   
    int n1 = -5, n2 = 4;
    int add = sum(n1,n2);
    cout << add << endl;
    int n3 = -3, n4 = -8;
    int add2 = sum(n3,n4);
    cout << add2 << endl;
    int n5 = 13, n6 = -6;
    int add3 = sum(n5,n6);
    cout << add3 << endl;
    int n7 = 5, n8 = -4;
    int add4 = sum(n7,n8);
    cout << add4 << endl;
    int n9 = 16, n10 = 10;
    int add5 = sum(n9,n10);
    cout << add5 << endl;
    return 0;
}

After testing this program, the output I am getting is:
-1
1
7
1
26

The second part of the output is not correct. When adding -3 and -8, it is supposed to come out to -11, but it is coming out to 1. Is there anyway I can fix this?

KISS - keep it short and simple. The sum() function should be simply this:

int sum( int x, int y)
{
    return x + y;
}

This results in this output:

-1
-11
7
1
26

Unless your definition of "sum" and mine differ! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.