211: Create a class to represent a mathematical vector with private data members for its components. Define constant objects and constant member functions to perform vector addition, subtraction, and scalar multiplication. Implement getter and setter functions for the vector components


// Create a class to represent a mathematical vector with private data members for
// its  components.  Define  constant  objects  and  constant  member  functions  to
// perform  vector  addition,  subtraction,  and  scalar  multiplication.  Implement
// getter and setter functions for the vector components

#include <iostream>
using namespace std;
class Vector
{
private:
    float X;
    float Y;
    float Z;

public:
    // constructors
    Vector() : X(0), Y(0), Z(0) {}
    Vector(float x = 0, float y = 0, float z = 0) : X(x), Y(y), Z(z) {}

    void printVector(string x) const { cout << x << '(' << X << ", " << Y << ", " << Z << ')' << endl; }

    // overloaded operators
    Vector operator+(const Vector &second) const;
    Vector operator-(const Vector &second) const;
    Vector operator*(const float &second) const;
};
Vector Vector ::operator+(const Vector &second) const { return Vector(X + second.X, Y + second.Y, Z + second.Z); }
Vector Vector ::operator-(const Vector &second) const { return Vector(X - second.X, Y - second.Y, Z - second.Z); }
Vector Vector ::operator*(const float &second) const { return Vector(X * second, Y * second, Z * second); }

int main()
{
    const Vector vec1(1, 2, 3), vec2(4, 5, 6);
    const int scalar = 5;
    vec1.printVector("Vector 1: ");
    vec2.printVector("Vector 2: ");

    Vector sum = vec1 + vec2;
    sum.printVector("Resultant vector after vector sum: ");

    Vector diff = vec1 - vec2;
    diff.printVector("Resultant vector after vector difference: ");

    Vector multiplication = vec1 * scalar;
    multiplication.printVector("Resultant vector after vector multiplication: ");

    return 0;
}


Comments

Popular posts from this blog

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_