Swift Program to Add Two Complex Numbers by Passing Class to a Function


In swift, a complex number is the combination of real and imaginary number. So we create a class to store the real and imaginary part of the complex number and then we pass this class in the function to find the sum of two complex numbers.

Algorithm

  • Step 1 − Create a class to store the real and imaginary part of the complex number.

  • Step 2 − Create a function named as ‘add’ which takes two class objects as a parameters and return the sum of the two complex numbers by adding the real and imaginary part of the two complex numbers.

  • Step 3 − Now create two instance of the class and pass them in the ‘add’ function to find the sum.

  • Step 4 − Print the output.

Example

In this example, we will first create a class named as ‘MyComplexNumber’ that has two properties real and imaginary to store real and imaginary part of the complex number. It also has a initialiser to set the initial value of real and imaginary properties. Then we create a function named as add() which takes two objects of ‘MyComplexNumber’ as a parameter and find the sum of complex numbers. To display the final result we create two instance of ‘MyComplexNumber’ and pass them in the ‘add’ function.

import Foundation
import Glibc

// Creating a class to store complex number
class MyComplexNumber {
   var real: Double
   var imaginary: Double
    
   init(real: Double, imaginary: Double) {
      self.real = real
      self.imaginary = imaginary
   }
}

// Function to add two complex numbers
func add(_ num1: MyComplexNumber, _ num2: MyComplexNumber) -> MyComplexNumber {
   let realNum = num1.real + num2.real
   let imaginaryNum = num1.imaginary + num2.imaginary
   return MyComplexNumber(real: realNum, imaginary: imaginaryNum)
}

// Creating instance of the class
let obj1 = MyComplexNumber(real: 3.0, imaginary: 4.0)
let obj2 = MyComplexNumber(real: 5.0, imaginary: 6.0)

let result = add(obj1, obj2)

print("Result: \(result.real) + \(result.imaginary)i")

Output

Result: 8.0 + 10.0i

Conclusion

So this is how we can add two complex numbers by passing class to a function. In the addition of complex numbers, we add the real part with real part and imaginary part with the imaginary part. We are not allowed to add real part with the imaginary part.

Updated on: 05-Apr-2023

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements