recursive function error in c++

Asked

Viewed 54 times

1

This recursive function should calculate the multiplication of two integers but it is always returning +1 in the result, someone can help me?

int multiplic(int m1, int m2){
    if(m2==0){
        return 1;
    }
    return m1 + multiplic(m1,m2-1);
}

1 answer

2


The problem is that at the end of the recursion you return 1 instead of returning 0 and that 1 is added to the value of the account.

Just change to 0:

int multiplic(int m1, int m2){
    if(m2==0){
        return 0; // <--
    }
    return m1 + multiplic(m1,m2-1);
}

Watch it run on Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.