C Programming Reference
 
C Programming Reference >> C  Programming Reference Question Bank >>

19/07/07 - 583 Views - Ratings :   4.5 of 5 / 2 Votes

Level - Advance
      

Question -

Write a program to multiply two number without using any' arithemetic operators (*,+,-,/,%) in C.
Answer -
#include <stdio.h>

long int addition(int a, int b)
{
int result = 0, carry;
carry = a&b;
if(carry)
{
result = a^b;
carry = carry << 1;
result = addition(carry, result);
}
else
{
result = a^b;
}
return result;
}

long int multiply(int a, int b)
{
int result=0, i=0;
while(i != b)
{
result = addition(result,a);
i = addition(i,1);
}
return result;
}

void main()
{
int a,b;
printf("Numbers: ");
scanf("%d %d", &a,&b);
printf("\n\nResult: %ld", multiply(a,b));
printf("\n");
}
 
Explanation -

Well this is not an easy question, what we do in this code is that we add two numbers using binary logic and multiply them using addition logice in a loop or recursion.

This logic is used in digital cirucits which are uses logic gates, so this is an also example of code derived from a digital circuit.

First we implement a function addition which takes two number to be added as parameter. This function adds two number bit by bit and also uses recursion call to add a carry value produced in the last step to next order bit.

Then to find product of two numbers it implemets a function called multiply which uses a loop to add a number again and again to itself to produce a cumulative result value. For eg to multiply A with B and to store result in C, C is intialised to 0 and a is added to it B times.

Answer is not so profound if you understand the explanation above.

Reader Comments -

Author Comments
Add Comments 


Name :    
Reply :   


Rating :

Code :
Code

 

 
© 2006 cencyclopedia.com