I am 9 grade, My math teacher asked me to add numbers with out using +
sign in C program.
I tried a - (-b) = a + b;
but my math teacher want some other option.
I am 9 grade, My math teacher asked me to add numbers with out using +
sign in C program.
I tried a - (-b) = a + b;
but my math teacher want some other option.
Use this function in your c program
int Add(int a, int b)
{
while (b)
{
// carry now contains common set bits of "a" and "b"
int carry = a & b;
// Sum of bits of "a" and "b" where at least one of the bits is not set
a = a ^ b;
// Carry is shifted by one so that adding it to "a" gives the required sum
b = carry << 1;
}
return a;
}
Use bitwise ^
and &
operators and recursion
int add(int x, int y){
return y == 0 ? x : add( x ^ y, (x & y) << 1);
}
P.S.: It is the recursive version of an algorithm proposed by vikas.
In Java using recursion-
public static int add(int a, int b){
if(b == 0) return a;
int sum = a ^ b;
int carry = (a & b) << 1;
return add(sum, carry);
}
In C-
int add(int a, int b){
if(b == 0) return a;
int sum = a ^ b;
int carry = (a & b) << 1;
return add(sum, carry);
}
Using Anti Log()
you can do that
Temp= Anti Log(a)* Anti Log(b);
a+b value is equals to log(Temp);
Works for integers not for double.
#include<stdio.h>
int add(int a, int b) {
return (int)&((char *)a)[b];
}
int main() {
printf("%d", add(5, 17));
getchar();
}
Not portable but doesn't use the "+" character. This casts a to a char pointer, adds b to it with [] and then casts it back to an int.