You are on page 1of 3

#include <iostream>

#include <string>
#include <time.h>
using namespace std;

class Complex{
float re;
float im;
public:
Complex(float r=0.0,float i=0.0){re=r;im=i;}
Complex(const Complex& c){re=c.re;im=c.im;}
void operator =(const Complex& c){re=c.re;im=c.im;}
Complex operator -()const{return Complex(-re,-im);}
Complex operator +(const Complex&)const;
Complex operator -(const Complex&)const;
Complex operator *(const Complex&)const;
Complex operator /(const Complex&)const;
friend ostream& operator <<(ostream&, const Complex&);
};
Complex Complex::operator +(const Complex& c)const{
float r=re+c.re;
float i=im+c.im;
return Complex(r,i);
}
Complex Complex::operator -(const Complex& c)const{
float r=re-c.re;
float i=im-c.im;
return Complex(r,i);
}
Complex Complex::operator *(const Complex& c)const{
float r=re*c.re-im*c.im;
float i=re*c.im+im*c.re;
return Complex(r,i);
}
Complex Complex::operator /(const Complex& c)const{
Complex nm = Complex(*this)*Complex(c.re,-c.im);
float dn = c.re*c.re + c.im*c.im;
float r=nm.re/dn;
float i=nm.im/dn;
return Complex(r,i);
}
ostream& operator <<(ostream& os, const Complex& c){
os << c.re;
if(c.im < 0)
os << c.im << "i";
else
os <<"+" << c.im << "i";
return os;
}
template<class T> class myStack{
T *ptr;
int size;
int top;
public:
myStack(int);
~myStack(){free(ptr);}
bool empty(){return top==-1;}
bool full(){return top==size-1;}
int gethold(){return top+1;}
void push(T v){ptr[++top]=v;}
T pop(){return ptr[top--];}
void display(int);
};
template<class T> myStack<T>::myStack(int s){
ptr = (T*)malloc(s*sizeof(T));
size=s;
top=-1;
}
template<class T> void myStack<T>::display(int k){
if(!empty()){
int h = gethold();
cout<<"Number of items popped up="<<h<<":"<<endl<<endl;
int i=0;
while(i<h){
cout<<"\t\t"<<pop();
i++;
if(i%k==0){
cout<<endl;
}
}
cout<<endl;
}
else
cout<<"Stack is empty."<<endl;
}
int main(int argc,char **argv) {
int n,m,k;
n = stoi(argv[1]);
m = stoi(argv[2]);
k = stoi(argv[3]);
myStack<Complex> stack(n);
srand(time(NULL));
for(int i=0; i<n; i++){
int re = rand();
int im = rand();
Complex c(re, im);
stack.push(c);
}
stack.display(k);
return 0;
}

OUTPUT:

> g++ project1.cpp -o project1 <press enter>

Run:

> ./project1 n m k <press enter>

Explanation:

1. Get the command-line values n, m, and k.

2. Create an n-dimensional complex number stack, then generate n random complex numbers and
push them into the stack. Meanwhile, show all of these numbers, k numbers per line.

3. Display all stack elements, k elements per line.

4. Generate two random complex numbers, c1 and c2, and display c1, c2, as well as the results of
addition c1+c2, subtraction c1-c2, multiplication c1*c2, and division c1/c2.

You might also like