Tuesday, 3 November 2015

How to add two numbers without using + operator or even without using arithmetic operator ?

Adding two numbers without using Arithmetic Operator

The following code does not uses any arithmetic operator to add two integers :


#1

int add(int , int );

int main(){

int num1, num2;
printf("Enter the numbers to be added: \n");
scanf("%d %d",&num1,&num2);

printf("Sum of the two numbers is: %d ", add(num1,num2));
retrun 0;

}

int add(int num1, int num2){

if(!num1)
return num2;

else return add((num1 & num2) >> 1, num1 ^  num2);

}



Now if we are to write a code to add two numbers without using + operator it can be done in the following ways:

#2

int main(){

int num1=5, num2=15;

while(num1--){
num2++;

}

printf("Sum is : %d ",num2);
return 0;
}


#3

int main(){

int num1=5, num2=15;

num1 = num1 - (- num2 );
printf("Sum is : %d ",num1);
return 0;
}


NOTE: We can use for loop as well instead of while loop in #2 method .

No comments:

Post a Comment