Create a class which store the real and imaginary part of a complex number . Add two complex number and display the result . To add 2 complex number, function having two object argument and and no return values
Objective
Write a C++ program to add two Complex Numbers by passing Objects as function arguments.
Algorithm / Approach
- Define a
class Complexwith public integersr(real) andi(imaginary). - Create a member function
add(Complex c1, Complex c2). - Inside
main(), create two Complex objectsc1andc2and read their values. - Call
c1.add(c1, c2)to add the real parts together, add the imaginary parts together, and print the formatted result.
main.cpp
#include<iostream>
using namespace std;
class Complex {
public :
int r,i;
void add(Complex c1, Complex c2 ) {
int x = c1.r+c2.r;
int y = c1.i+c2.i;
cout<<"Sum = "<< x<<" +i"<< y;
}
};
int main() {
Complex c1,c2;
cout<<"Enter Real & Imag. of Num1 :";
cin>>c1.r>>c1.i;
cout<<"Enter Real & Imag. of Num2 :";
cin>>c2.r>>c2.i;
c1.add(c1,c2);
return 0;
}
Expected Output
Enter the Real and Imag. of Num1 :5 10 Enter the Real and Imag. of Num2 :6 20 Sum = 11 +i30
Explanation of the Program
- Just like integers and strings, whole Objects can be passed into functions as arguments!
- A Complex Number has a Real part and an Imaginary part (e.g., 5 + 10i). To add two complex numbers mathematically, you add the real parts together, and the imaginary parts together independently.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)