Wednesday 12 October 2011

OPERATIONS ON COMPLEX NUMBERS USING FILES AS STORAGE


OPERATIONS ON COMPLEX NUMBERS USING FILES AS STORAGE

AIM:
To write a C++ program to perform addition of complex numbers using files.

ALGORITHM:

Step 1: Start the program.
Step 2: Create a class called COMPLEX and create its members: real and imaginary.
Step 3: Generate the random numbers by using rand() function.
Step 4: Write the randomly generated numbers in a file called “complex1.txt”.
Step 5: Add the two complex numbers.
Step 6: Store the Resultant complex number in another file called “result.txt”
Step 7: Display the resultant value.
Step 8: Stop the program.

PROGRAM:

#include<iostream.h>
#include<conio.h>
#include<fstream.h>
#include<stdlib.h>
#include<time.h>
class complex
{
public:
int real;
int imag;
complex(int r, int i)
{
real = r;
imag = i;
}
complex()
{
real = imag = 0;
}
void display(void);
};
void complex::display(void)
{
cout<<real<<((imag<0)?"-i":"+i")<<imag<<"\n";
}
void main()
{
clrscr();
ofstream ocom("complex1.txt");
float real,imag;
time_t ti;
srand((unsigned) time(&ti));
real = rand()%100;
imag = rand()%100;
ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"+";
real = rand()%100;
imag = rand()%100;
ocom<<"("<<real<<((imag<0)?"-i":"+i")<<imag<<")"<<"\n";
ocom.close();
ifstream icom("complex1.txt");
char no,t,ch,op;
icom>>no;
icom>>real;
icom>>ch;
icom>>no;
icom>>imag;
imag=(ch=='+')?imag:-imag;
icom>>no;
icom>>op;
complex a(real,imag);
icom>>no;
icom>>real;
icom>>ch;
icom>>no;
icom>>imag;
imag=(ch=='+')?imag:-imag;
icom>>no;
icom>>op;
complex b(real,imag);
complex c;
switch(op)
{
case '+':
c.real = a.real+b.real;
c.imag = a.imag+b.imag;
break;
case '-':
c.real = a.real-b.real;
c.imag = a.imag-b.imag;
break;
case '*':
c.real = (a.real*b.real)-(a.imag*b.imag);
c.imag = (a.real*b.imag)+(a.imag*b.real);
break;
case '/':
float qt;
qt = b.real*b.real+b.imag*b.imag;
c.real = (a.real*b.real+a.imag*b.imag)/qt;
c.imag = (a.imag*b.real-a.real*b.imag)/qt;
break;
default:
cout<<"\n Invalid";
}
cout<<"\n complex 1:";
a.display();
cout<<"\n complex 2:";
b.display();
cout<<"\n Resultant complex:";
c.display();
ofstream out("result.txt");
out<<"("<<c.real<<((c.imag<0)?"-i":"+i")<<c.imag<<")";
out.close();
}

OUTPUT:
complex1.txt:
(0+i72)+(39+i71)
result.txt
(39+i143)

RESULT:
Thus the program for addition of complex numbers using files was executed.

0 comments:

Post a Comment