Write a C program to multiply two numbers without using * multiplication operator.
Given two numbers, both numbers are positive. Write a program to multiply two numbers without using * multiplication operator. This problem is bit tricky as we are not allowed to use multiplication operator .
We can use multiple approaches to solve this problem. In this tutorial, i am going to explain how to multiply two numbers using recursion as well as using iterative approach.
C Programs on Arrays, Strings, Linked List, Stack, Queues.
Programming questions for practice
C Program to Multiply two numbers without using * Multiplication Operator
1. First Method: Using Recursion to multiply two numbers without using *. We can easily calculate the product of two numbers using recursion without using * multiplication operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
//Using recursion to multiply two numbers #include <stdio.h> int multiply(int firstnum, int secondnum){ // If second number is zero then the product is zero. if(secondnum == 0){ return 0; } else { // Add first num, until second num is equal to zero. return (firstnum + multiply(firstnum, secondnum-1)); } } main() { int firstnum, secondnum, prod; printf("Enter two numbers \n"); scanf("%d %d",&firstnum,&secondnum); // Function call prod = multiply(firstnum,secondnum); printf("Multiplication of two numbers is %d",prod); } |
2. Second Method – Iterative Approach to multiply two numbers without using *.
I have explained how to solve this problem using recursion. Let’s multiply two numbers using an iterative method.
If you don’t know the difference between recursive and iterative approach then check my previous tutorial on Difference between recursion and iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> main() { int firstnum, secondnum; int prod = 0; printf("Enter two numbers \n"); scanf("%d %d", &firstnum, &secondnum); /* If secondnum greater than zero. */ while(secondnum){ /* Add the value of firstnum in prod. */ prod += firstnum; /* Decrement the value of secondnum. */ secondnum--; } printf("Multiplication of two numbers is %d",prod); } |
b) We can solve this problem using for loop as well.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <stdio.h> int main(void) { int firstnum, secondnum; int prod = 0,i; printf("Enter two numbers \n"); scanf("%d %d",&firstnum,&secondnum); for(i = 1; i <= secondnum; i++){ /* Add the value of firstnum in prod. */ prod += firstnum; } printf("Multiplication of two numbers is %d",prod); return 0; } |
C Program to swap two numbers using third variable