Web Toolbar by Wibiya

Pages

Sunday, June 12, 2011

Multiply two integers without using * operator or while/for loop.

Solution #1: This can be done using recursion,

int multiply(int a, int c)
{
    static int b = 0;
    if(c == 0)
        return b;
    else if(c<0)
    {
        b-=a;
        return multiply(a,++c);
    }
    else
    {
        b+=a;
        return multiply(a,--c);
    }
}

void main()
{
    printf("Product = %d\n", multiply(5, -2));
}

No comments: