Kotlin Program to Add Two Complex numbers


In this article, we will understand how to add two complex numbers in Kotlin. They have the ‘I’ that is, an imaginary part associated with it.

Below is a demonstration of the same −

Suppose our input is

15 +i24 and 3 +i7

The desired output would be

18 +i31

Algorithm

  • Step 1 − Start

  • Step 2 − Declare three Complex numbers: inputValue1, inputValue2 and myResult

  • Step 3 − Hardcode the complex number values

  • Step 4 − Define a function addComplexNumber, wherein you add the real numbers and the imaginary numbers separately and return the result.

  • Step 5 − Store the result in myResult variable.

  • Step 6 − Display the result

  • Step 7 − Stop

Example 1

In this example, we will add two complex numbers in Kotlin

class Complex(internal var real: Double, internal var imaginary: Double) fun main() { val inputValue1 = Complex(15.0, 24.0) val inputValue2 = Complex(3.0, 7.0) System.out.printf("The input values are (%.1f, i%.1f) and (%.1f, i%.1f)
"
,inputValue1.real, inputValue1.imaginary , inputValue2.real, inputValue2.imaginary) val myResult = Complex(0.0, 0.0) myResult.real = inputValue1.real + inputValue2.real myResult.imaginary = inputValue1.imaginary + inputValue2.imaginary System.out.printf("The sum of the complex number is %.1f + i%.1f", myResult.real, myResult.imaginary) }

Output

The input values are (15.0, i24.0) and (3.0, i7.0) 
The sum of the complex number is 18.0 + i31.0

Example 2

In this example, we will add two complex numbers in Kotlin using a custom function

class Complex(internal var real: Double, internal var imaginary: Double) fun main() { val input1 = Complex(15.0, 24.0) val input2 = Complex(3.0, 7.0) val myResult: Complex System.out.printf("The input values are (%.1f, i%.1f) and (%.1f, i%.1f)
"
,input1.real, input1.imaginary , input2.real, input2.imaginary) myResult = addComplexNumbers(input1, input2) System.out.printf("The sum of the complex number is %.1f + i%.1f", myResult.real, myResult.imaginary) } fun addComplexNumbers(input1: Complex, input2: Complex): Complex { val myResult = Complex(0.0, 0.0) myResult.real = input1.real + input2.real myResult.imaginary = input1.imaginary + input2.imaginary return myResult }

Output

The input values are (15.0, i24.0) and (3.0, i7.0)
The sum of the complex number is 18.0 + i31.0

Updated on: 13-Oct-2022

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements