program in C and C++ for half adder

program in C and C++ for half adder

Half Adder


Half adder is used for adding two bit.There are two input and two output in half adder.

Truth Table:

Circuit Diagram:

Sum = A XOR B
Carry = A AND B

Program in C:




 #include <stdio.h>
 #include <conio.h>

 typedef char bit;
 bit carry=0;
bit halfadd(bit A,bit B){
 carry=A&B;
   return A^B;
 }
int main()
{
 int i,j,result;
 printf("A   B  |  S  Carry\n");
 for(i=0;i<2;i++)
 {
  for(j=0;j<2;j++)
  {
   result=halfadd(i,j);
   printf("%d   %d  |  ",i,j);
   printf("%d   %d\n",result,carry);
  }
 }
 return 0;
}

Output:



 A   B  |  S  Carry
 0   0  |  0    0
 0   1  |  1    0
 1   0  |  1    0
 1   1  |  0    1

--------------------------------
Process exited after 0.1519 seconds with return value 0
Press any key to continue . . .


Program in C++:




 #include <iostream>
 using namespace std;
 
 typedef char bit;
bit halfadd(bit A,bit B,bit C){
    if(C==0)
      return A&B;
    else
      return A^B;
 }
int main()
{
 int i,j,result;
 int carry;
 cout<<"A   B  |  S  Carry\n";
 for(i=0;i<2;i++)
 {
  for(j=0;j<2;j++)
  {
   result=halfadd(i,j,1);
   carry=halfadd(i,j,0);
   cout<<i<<"   "<<j<<"  |  ";
   cout<<result<<"   "<<carry<<"\n"; 
  }
 }
 return 0;
}

Output:



 A   B  |  S  Carry
 0   0  |  0    0
 0   1  |  1    0
 1   0  |  1    0
 1   1  |  0    1

--------------------------------
Process exited after 0.1519 seconds with return value 0
Press any key to continue . . .


Algorithm:

STEP 1: Start

STEP 2: Define 'halfadd' function

STEP 3: Perform AND operation on binary numbers and store it as carry

STEP 4: Perform XOR operation on binary numbers and store it as sum

STEP 5: Invoke main function

STEP 6: Initialize variables

STEP 7: Check for condition (i<2), if Condition is true, go to step 8 otherwise go to step 11

STEP 8: Check for condition (j<2), if Condition is true, go to further step otherwise go to step 7

STEP 9: Call 'halfadd' function for value of sum and carry

STEP 10: Print all values

STEP 11: Stop

Comments :

Post a Comment