LAB-9
Define a function which takes TWO objects representing complex numbers and
returns new complex number with a addition of two complex numbers. Define a
suitable class ‘Complex’ to represent the complex number. Develop a program to
read N (N >=2) complex numbers and to compute the addition of N complex
numbers.
class Complex:
def initComplex(self):
self.realPart = int(input("Enter the Real Part: "))
self.imgPart = int(input("Enter the Imaginary Part: "))
def display(self):
print(self.realPart, "+", self.imgPart, "i", sep="")
def sum(self, c1, c2):
self.realPart = c1.realPart + c2.realPart
self.imgPart = c1.imgPart + c2.imgPart
# Create Complex number objects
c1 = Complex()
c2 = Complex()
c3 = Complex()
# Input and Display first complex number
print("Enter first complex number")
c1.initComplex()
print("First Complex Number: ", end="")
c1.display()
# Input and Display second complex number
print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ", end="")
c2.display()
# Sum and Display result
print("Sum of two complex numbers is ", end="")
c3.sum(c1, c2)
c3.display()
Algorithm:
1. Start
2. Define a class Complex with three methods:
• initComplex(self):
• Ask the user to enter the real part and imaginary part.
• Store these values in self.realPart and self.imgPart.
• display(self):
• Print the complex number in the format: real part + imaginary part i.
• sum(self, c1, c2):
• Set self.realPart as the sum of c1.realPart and c2.realPart.
• Set self.imgPart as the sum of c1.imgPart and c2.imgPart.
3. Create three objects c1, c2, and c3 of the class Complex.
4. Input first complex number:
• Call c1.initComplex() to read the first complex number.
• Call c1.display() to show the entered first complex number.
5. Input second complex number:
• Call c2.initComplex() to read the second complex number.
• Call c2.display() to show the entered second complex number.
6. Calculate the sum:
• Call c3.sum(c1, c2) to add the two complex numbers.
7. Display the result:
• Call c3.display() to print the sum of the two complex numbers.
8. End
Output:
Enter first complex number
Enter the Real Part: 3
Enter the Imaginary Part: 4
First Complex Number: 3+4i
Enter second complex number
Enter the Real Part: 2
Enter the Imaginary Part: 3
Second Complex Number: 2+3i
Sum of two complex numbers is 5+7i