beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C++ Program to Add Complex Numbers

By Chaitanya Singh | Filed Under: C++ Programs

This program takes two complex numbers (entered by user) as input and displays the sum of them.

Example: Program to add two complex numbers entered by user

#include <iostream> 

using namespace std;

class complex_number
{
   public :
      int real, imag;
};

int main()
{
   complex_number num1, num2, sum;

   //getting the value of first complex number from user
   cout << "Enter real and imaginary parts of first complex number:"<<endl; 
   cin >> num1.real >> num1.imag;

   //getting the value of second complex number from user
   cout << "Enter real and imaginary parts of second complex number:"<<endl; 
   cin >> num2.real >> num2.imag;

   //addition of real and imaginary parts of complex numbers entered by user
   sum.real = num1.real + num2.real;
   sum.imag = num1.imag + num2.imag;

   //displaying the sum of complex numbers
   if ( sum.imag >= 0 )
      cout << "Sum of two complex numbers = " << sum.real << " + " << sum.imag << "i";
   else
      cout << "Sum of two complex numbers = " << sum.real << " - " << sum.imag << "i";

   return 0;
}

Output:

Enter real and imaginary parts of first complex number:
4 6
Enter real and imaginary parts of second complex number:
2 3
Sum of two complex numbers = 6 + 9i

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap