binary addition using c++

Thread Starter

Gizew

Joined Nov 29, 2007
17
hey everybody!

i wnat to write a c++ code that manipulates a binary addition.
here is what i made:

for(i=1;i<=n;i++)
{
d=(a+[bi])/2;
if(a==1)
c=0;
else
c=1;
}
// a and b are arrays of size n and c is the sum in binary form.
but the problem arises how to transfer the carry to the next.
i have tried some what like this:
if(a==1&&b==1)
c[i+1]=c[i+1]+1;
i am not that much sure whether it is correct or not.
but even in this there is a problem of how to call back the above code.
(i am not saying that a problem of calling a function).

can u help u friends?:confused:
 

Mark44

Joined Nov 26, 2007
628
Inside your loop, at each step you need to keep track of whether a carry occurs. If it does, you'll need to do the addition in the next loop iteration. So each loop iteration you'll need to add a + b + carry. The first iteration of your loop, carry will necessarily be 0.

Having said that, it's not clear to me what kinds of values are in your a and b arrays. Are the elements 1s and 0s?

What's the purpose of the d array? And why do you put (a + b)/2 into d?

BTW, your loop is running from i = 1 to i = n. This means that you aren't looking at the 0-th element of any of your arrays. The common practice is to have loops like so: for(i = 0; i < n i++)
 
Top