In this example, you will learn about C program to multiply two numbers without using multiplication operator (*).
You might be wondering how it is possible:
Let’s see following example.
4 * 5 = 20 How it works? 4 added 5 times (4 + 4 + 4 + 4 + 4) = 20
Let’s implement this logic in the source code with three different methods.
First, go through following articles for proper understanding.
//Multiplication of two numbers
#include <stdio.h>
int main()
{
int x, y; //declaring two integer variable
int product = 0; //initializing product to zero
printf("Enter two integers:\n");
scanf("%d%d", &x, &y);
//loop to calculate product
while(y != 0)
{
product += x;
y--;
}
printf("\nProuduct = %d\n", product);
return 0;
}
Output
[adsense1]
//Multiplication of two numbers using recursive function
#include <stdio.h>
//function prototype for recursive function
int product( int n1, int n2);
int main ()
{
int x, y;
printf("Enter two integers:\n");
scanf("%d%d", &x, &y);
//calling recursive function
printf("\nProuduct = %d\n", product(x, y));
return 0;
}
//body of recursive function
int product(int n1, int n2)
{
if(n2 == 0)
return 0;
if(n2 > 0)
return (n1 + product(n1, n2 - 1));
if(n2 < 0)
return -product(n1, -n2);
}
Output
Explanation
In the above program, we have used product()
recursion function for multiplying two numbers.
product()
function uses three if
condition to check whether the number entered by the user is equal, greater or smaller than zero.
//Multiplication of two numbers using pointer
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, y;
char *p;
printf("Enter two integers:\n");
scanf("%d%d", &x, &y);
p = (char *)x;
while(--y)
p = &p[x];
printf("\nProuduct = %d\n", p);
free(p);
return 0;
}
Output
Explanation
In the above program, we have used a pointer for multiplication of two numbers.
At first, we have placed the content of x
into p
using p = (char *) x.
Inside while loop, we have added the content of x
to p
using p = &p[x].
Finally, we have freed the pointer memory using free(p).