Open In App

Python program to implement Half Adder

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Half Adder in Digital Logic

Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e sum and carry of two inputs.

Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of numbers. The half adder is able to add two single binary digits and provide the output plus a carrying value. It has two inputs, called A and B, and two outputs S (sum) and C (carry).

Logical Expression:  

Sum = A XOR B  
Carry = A AND B 

Truth Table:

Examples:

Input : 0 1

Output: Sum=1, Carry=0

Explanation: According to logical expression Sum=A XOR B  i.e 0 XOR 1 =1 , Carry=A AND B  i.e 0 AND 1 =0

Input : 1 1

Output: Sum=0, Carry=1

Explanation: According to logical expression Sum=A XOR B  i.e 1 XOR 1 =0 , Carry=A AND B  i.e 1 AND 1 =1

Approach:

  • We take two inputs A and B.
  • XOR operation on A and B gives the value of the sum.
  • AND operation on A and B gives the value of Carry.

Below is the implementation.

Python3




# Function to print sum and carry
def getResult(A, B):
   
    # Calculating value of sum
    Sum = A ^ B
     
    # Calculating value of Carry
    Carry = A & B
     
    # printing the values
    print("Sum ", Sum)
    print("Carry", Carry)
 
 
# Driver code
A = 0
B = 1
 
# passing two inputs of halfadder as arguments to get result function
getResult(A, B)


Output:

Sum  1
Carry 0

Method#2:Using numpy:

Algorithm:
 

  1. Import the required NumPy library.
  2. Define the function half_adder(A, B) which takes two input bits A and B as arguments.
  3. Calculate the Sum of the two input bits using the NumPy bitwise_xor() function which returns the bitwise XOR of two input arrays.
  4. Calculate the Carry of the two input bits using the NumPy bitwise_and() function which returns the bitwise AND of two input arrays.
  5. Return the calculated Sum and Carry values.
  6. Define the input bits A and B.
  7. Call the half_adder() function with the input bits A and B and store the returned Sum and Carry values.
  8. Print the calculated Sum and Carry values.

Python3




import numpy as np
def half_adder(A, B):
    Sum = np.bitwise_xor(A, B)
    Carry = np.bitwise_and(A, B)
    return Sum, Carry
# Driver code
A = 0
B = 1
Sum, Carry = half_adder(A, B)
print("Sum:", Sum)
print("Carry:", Carry)
#This code is contributed by Jyothi Pinjala.


Output:

Sum: 1
Carry: 0

Time complexity:
The time complexity of this code is O(1) since the calculations involved in the half_adder() function take constant time regardless of the input values.
Auxiliary Space:
The space complexity of this code is O(1) since the function only uses a constant amount of memory to store the input variables, intermediate variables, and output variables.



Last Updated : 25 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads