You are on page 1of 3

# 20/08/2013

c - Subtracting two numbers without using '-' operator - Stack Overflow

Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Tell me more

×

Subtracting two numbers without using '-' operator

i tried with the following code , but i can't understand why it's giving me wrong answer. i am computing the 2's complement and adding with another no. # i n c l u d e< s t d i o . h > i n ta d d ( i n ta ,i n tb ){ w h i l e( a ){ a=( a&b )< <1 ; b=a ^ b ; } r e t u r nb ; } i n ts u b ( i n ta ,i n tb )/ /a d daw i t hb ' s2 ' sc o m p l e m e n t . { r e t u r n( a d d ( a ,a d d ( ~ b ,1 ) ) ) ; } i n tm a i n ( ){ i n ta ,b ,r e s ; a=3 ,b=1 ; r e s=s u b ( a ,b ) ; p r i n t f ( " % d \ n " ,r e s ) ; r e t u r n0 ; }
c bitwise

edited Aug 8 '10 at 13:54 Carlos Muñoz 4,699 2 20 46

asked Aug 7 '10 at 13:45 pranay 619 7 26

3

s u b ( ) is giving you the wrong result because a d d ( ) is wrong. The logic in s u b ( ) is fine. – NullUserException ♦ Aug 7 '10 at 13:49 What's wrong with -? What's wrong with a + b? – Charles Bailey Aug 7 '10 at 13:51 This brings back memories too. Our professor wouldn't let us use loops, or i f statements for that matter. – NullUserException ♦ Aug 7 '10 at 13:51

1

@Charles It's homework. – NullUserException ♦ Aug 7 '10 at 13:51 @NullUserException: So what if it's homework; it's also tagged as C. + and - are always available in C. This feels very much like "not a real question" to me. – Charles Bailey Aug 7 '10 at 14:04