How can I perform multiplication without the '*' operator?

前端 未结 30 1585
别跟我提以往
别跟我提以往 2020-12-01 01:47

I was just going through some basic stuff as I am learning C. I came upon a question to multiply a number by 7 without using the * operator. Basically it\'s like this

<
30条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-01 02:30

    By making use of recursion, we can multiply two integers with the given constraints.

    To multiply x and y, recursively add x y times.

         #include
         /* function to multiply two numbers x and y*/
         int multiply(int x, int y)
         {
            /* multiplied with anything gives */
            if(y == 0)
            return 0;
    
            /* Add x one by one */
            if(y > 0 )
            return (x + multiply(x, y-1));
    
            /* the case where y is negative */
            if(y < 0 )
            return -multiply(x, -y);
         }
    
         int main()
         {
           printf("\n %d", multiply(5, -11));
           getchar();
           return 0;
         }
    

提交回复
热议问题