Thursday, February 29, 2024

Program 1 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 1 Write a class to represent a complex number which has member functions to do the following

 

BCA

Object Oriented Programming using C++ Practical

Madras University 

Program 1

Write a class to represent a complex number which has member functions to do the following a. Set and show the value of the complex number b. Add, subtract and multiply two complex numbers c. Multiplying the complex number with a scalar value 

SOURCE CODE:
#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
class ComplexNumber {
private:
    double real;
    double imaginary;

public:
ComplexNumber() {
real = 0;
imaginary = 0;
    }

    void set_value(double realPart, double imaginaryPart) {
real = realPart;
imaginary = imaginaryPart;
    }

 void show_value() {
     if(imaginary<0)
cout << real << " - " << -imaginary << "i" << endl;
else
cout << real << " + " << imaginary << "i" << endl;
 }

    void add(ComplexNumber c2) {
double r = real + c2.real;
double i = imaginary + c2.imaginary;
cout<<"Sum of two Complex numbers:"<<endl;
result(r, i);
    }

    void subtract(ComplexNumber c2) {
double r = real - c2.real;
double i = imaginary - c2.imaginary;
cout<<"Difference of two Complex numbers:"<<endl;
result(r, i);
  }

    void multiply(ComplexNumber c2) {
double r = real * c2.real - imaginary * c2.imaginary;
double i = real * c2.imaginary + imaginary * c2.real;
cout<<"Multiplication of two Complex numbers:"<<endl;
result(r, i);
}

    void multiply_scalar(double scalar) {
double r = real * scalar;
double i = imaginary * scalar;
result(r, i);
}

    void result(double real, double imaginary) {
if(imaginary<0)
cout << real << " - " << -imaginary << "i" << endl;
else
cout << real << " + " << imaginary << "i" << endl;

    }
};

int main() {
    ComplexNumber c1,c2;
    double r1,r2,i1,i2,scalar;
    clrscr();
    cout<<"Enter the real and imaginary part of 1st complex number:";
    cin>>r1;
    cin>>i1;
    cout<<"Enter the real and imaginary part of 2nd complex number:";
    cin>>r2;
    cin>>i2;
    c1.set_value(r1,i1);
    c2.set_value(r2,i2);

    // Set and show value
    cout<<"Complex Numbers:"<<endl;
    c1.show_value();
    c2.show_value();

    // Add
    c1.add(c2);
    // Subtract
    c1.subtract(c2);

    // Multiply
    c1.multiply(c2);

    // Multiply with scalar
    cout<<"Enter scalar value to multiply with complex numbers: "<<endl;
    cin>>scalar;
    c1.multiply_scalar(scalar);
    c2.multiply_scalar(scalar);
     getch();
    return 0;
}


SAMPLE OUTPUT:




No comments:

Post a Comment

Program 12 BCA Madras University BCA Object Oriented Programming using C++ Practical Madras University Program 12 Implement a telephone directory using files

  BCA Object Oriented Programming using C++ Practical Madras University  Program 12  Implement a telephone directory using files SOURCE CODE...