Idea 1:-
Half adder logic
A half adder has two inputs for the two bits to be added and two outputs one from the ‘sum’ and the other from the ‘carry’ into the higher adder position. A circuit is called a carrying signal from the addition of the sum of the less significant bits from the X-OR gate the out from AND gate.
Truth table :-
A |
B |
SUM |
CARRY |
0 |
0 |
0 |
0 |
0 |
1 |
1 |
0 |
1 |
0 |
1 |
0 |
1 |
1 |
0 |
1 |
In the truth
table. you can see I have provided all
possible combinations of A and B. Now if
you observe the truth table clearly, the
sum is nothing but A X-or B. As we know
in X-or two different bits give the output
1.
Carry is
equal to A and B because we have like 1, 1 input combination the output is
equal to one. Therefor
SUM = A XOR B
Carry =
A AND
B
C program
#include
<stdio.h>
int main()
{
int a, b, sum, carry;
printf("a=");
scanf("%d", &a);
printf("b=");
scanf("%d", &b);
while (b != 0)
{
sum = a ^ b;
carry = (a & b) << 1;
a = sum;
b = carry;
}
printf("sum = %d", sum);
return 0;
}
Explanation of program
Step 1: Declared two integer type variable a and b. sum and carry
taken from to logic gate which is XOR and AND.
Step 2: Give the input in an integer type
variable ‘a’ and ‘b’ by scanf() function.
Step 3: Use while loop check b is not equal
to zero. the sum is equal to a^b then after carry is equal to a&b <<1
. and stored the value of sum in a. and stored the value of carry in b.
Step 4: Print the sum.
Output:-
Idea 2
Using while loop
C program
#include
<stdio.h>
int main()
{
int a, b;
printf("a=");
scanf("%d", &a);
printf("b=");
scanf("%d", &b);
if (b > 0)
{
while (b != 0)
{
a++;
b--;
}
}
else if (b < 0)
{
while (b != 0)
{
a--;
b++;
}
}
printf("sum = %d\n", a);
return 0;
}
Output:-
Good Content
ReplyDeleteThanks for the feedback!
Delete