Program 9
Program 9
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.
#Complex.py
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
return f"{self.real} + {self.imaginary}i"
def read_complex_numbers(n):
complex_numbers = []
for i in range(n):
real = float(input(f"Enter the real part of complex number {i + 1}: "))
imaginary = float(input(f"Enter the imaginary part of complex number {i + 1}: "))
complex_numbers.append(Complex(real, imaginary))
return complex_numbers
def sum_complex_numbers(complex_numbers):
total = Complex(0, 0)
for cn in complex_numbers:
total += cn
return total
# Main program
try:
n = int(input("Enter the number of complex numbers (N >= 2): "))
if n < 2:
print("N must be at least 2.")
exit()
complex_numbers = read_complex_numbers(n)
total = sum_complex_numbers(complex_numbers)
print("The sum of the complex numbers is:", total)
except ValueError:
print("Please enter valid numbers.")
OUTPUT 1
OUTPUT 2
Brief Explanation:
1. Class Design:
2. Reading Input:
3. Summation:
o The sum_complex_numbers function adds all the complex numbers in the list.
4. Validation:
o The program ensures that at least 2 complex numbers are entered, handling
invalid inputs gracefully.