program in C and C++ for half subtractor

program in C and C++ for half subtractor

Half Subtractor


Half subtractor is used to perform subtraction for two bit.There are two input and two output in half subtractor.

Truth Table:

Circuit Diagram:

Diff = A XOR B
Borrow = A' AND B

Program in C:




 #include <stdio.h>

  typedef char bit;
   bit borrow=0;
bit halfsub(bit A,bit B){
 borrow=!A&B;
 return A^B;
      }
int main()
{
 int i,j,result;
 printf("A   B  |  Diff  Borrow\n");
 for(i=0;i<2;i++)
 {
  for(j=0;j<2;j++)
  {
   result=halfsub(i,j);
   printf("%d   %d  |   ",i,j);
   printf("%d    %d\n",result,borrow);
   }
  }
 return 0;
}

Output:



A   B  |  Diff  Borrow
0   0  |   0      0
0   1  |   1      1
1   0  |   1      0
1   1  |   0      0

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




Program in C++:




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

Output:



 A   B  |  S  Borrow
 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 'halfsub' function

STEP 3: Perform the operation (A' NOT B) on binary numbers A and B and store it as borrow

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

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 'halfsub' function for value of diff and borrow

STEP 10: Print all values

STEP 11: Stop

Comments :

Post a Comment