Program to Perform Arithmetic Operations Without Using Arithmetic Operators in C

Question
It is one of most frequently asked interview question to perform any arithmetic operations(add,subtract,multiply,divide) without using arithmetic operators.
Logic
- The logic is simple. We have to use loop and manipulate the value of one variable with value of another variable. This will help us calculate the addition and subtraction.
- Nested loops can help us to perform Division and multiplication. We perform same addition/ subtraction operation more number of times to get the result.
Program:
[code lang=”c”]
#include <stdio.h>
//Compiler version gcc 6.3.0
//Program to perform arithmetic operations
//Without arithmetic operator
int main()
{
int a,b,c,i=0,j=0,t=0,temp; //intialization for using in below programs
int n; // initialize for switch
printf("Enter First Value\n");
scanf("%d",&a); // read value 1
printf("Enter Second Value\n");
scanf("%d",&b);// read value 2
printf("Choose Operation:\n");
printf("1.ADD\n2.SUBTRACT\n3.MULTIPLE\n4.DIVIDE\n");
scanf("%d",&n);// read integer for switch case
/*
Before move to perform operation, we should change
the big value to variable a and small value to variable b.
Its minimize the execution time.
*/
//Swapping function
if(a<b)
{
t=b;
b=a;
a=t;
}
switch(n)
{
case 1: //for addition operation
while(b>i) // check b(low value) with i
{
a++; //increment once
i++; //increment i
} // the loop execute until the b equals to i and a was incremented.
//now the value of a is equal to a+b
printf("%d",a);
break;
case 2://for subtraction operation
while(b>i) // check b(low value) with i
{
a–;//decrement once
i++; //increment i
}// the loop execute until the b equals to i and a was incremented.
//now the value of a is equal to a-b
printf("%d",a);
break;
case 3://for multiplication operation
temp=a; //in that time we use same addition loop with a times.so we use nested loop.
i=1;
while(b>i)
{
while(temp>j)
{
a++;
j++;
}
j=0;
i++;
}
printf("%d",a);
break;
case 4: //for division operation
i=0;c=0;
t=b; //in that time we use same subtraction loop with a times.so we use nested loop.
while(a>t)
{
while(b>i)
{
a–;
i++;
}
i=0;
c++; //we count the number of times subtracted
}
printf("%d",c+1); //print the last count of subtraction value
break;
break;
}
return 0;
}
[/code]
Keywords:
Program to Perform Arithmetic Operations without Arithmetic Operator
Program to Perform Addition Operation without Arithmetic Operator
Program to Perform Subtraction Operation without Arithmetic Operators
Program to Perform Multiplication Operation without Arithmetic Operators
Program to Perform Division Operation without Arithmetic Operators