Write a C++ program using the concept of OOP to find the sum of the right diagonals of a matrix


//Write a C++ program using the concept of OOP to find the sum of the right diagonals of a matrix
 
#include <iostream>
 
// Matrix class
class Matrix
{
private:
    int rows, cols;
    int** data;
 
public:
    // Constructor that takes the number of rows and columns as parameters and creates a matrix with the given dimensions
    Matrix(int rows, int cols) : rows(rows), cols(cols)
    {
        // Allocate memory for the matrix
        data = new int*[rows];
        for (int i = 0; i < rows; i++)
            data[i] = new int[cols];
    }
 
    // Destructor that frees the memory allocated for the matrix
    ~Matrix()
    {
        for (int i = 0; i < rows; i++)
            delete[] data[i];
        delete[] data;
    }
 
    // Function to fill the matrix with values
    void fill(int value)
    {
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                data[i][j] = value;
    }
 
    // Function to print the matrix
    void print()
    {
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
                std::cout << data[i][j] << " ";
            std::cout << std::endl;
        }
    }
 
    // Function to find the sum of the right diagonals of the matrix
    int sum_right_diagonals()
    {
        int sum = 0;
 
        for (int i = 0; i < rows; i++)
            sum += data[i][i];
 
        for (int i = 0; i < rows; i++)
            sum += data[i][cols - i - 1];
 
        return sum;
    }
};
 
int main()
{
    // Create a matrix with 3 rows and 3 columns
    Matrix matrix(3, 3);
 
    // Fill the matrix with the values 1, 2, 3, 4, 5, 6, 7, 8, 9
    matrix.fill(1);
 
    // Print the matrix
    matrix.print();
 
    // Find the sum of the right diagonals of the matrix
    int sum = matrix.sum_right_diagonals();
 
    // Print the sum
    std::cout << "Sum of right diagonals: " << sum << std::endl;
 
    return 0;
}
/*
=========Output===========
1 1 1
1 1 1
1 1 1
Sum of right diagonals: 6 

*/ 

No comments:

Post a Comment