-
Notifications
You must be signed in to change notification settings - Fork 0
/
45.Matrices_SymmetricMatrix.cpp
68 lines (61 loc) · 1.13 KB
/
45.Matrices_SymmetricMatrix.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* symmetric matrix
* M[i,j] = nz ;i<=j
* [1 2 3
* 2 1 4
* 3 4 1]
*
* A^t = A
FORMULA :
*/
//Either upper or lower traingular matrix will do.
#include<iostream>
using namespace std;
class lt_matrix{
int n;
int *A;
public:
lt_matrix(){
cout<<"Enter dimension: ";
cin>>n;
//number of elements - n*(n+1)/2
A = new int[n*(n+1)/2];
}
void set_all();
int get(int i, int j);
void display();
~lt_matrix(){
delete []A;
}
};
void lt_matrix::set_all(){
cout<<"Enter "<<n*(n+1)/2<<" elements: ";
for(int i=0;i<n*(n+1)/2;i++)
cin>>A[i];
}
int lt_matrix::get(int i,int j){
int temp;
//get element at given index
if(i<=j)
return A[n*(i) - (i*(i-1)/2) + j-i];
else
//swap i,j
temp = j;
j = i;
i = temp;
return A[n*(i) - (i*(i-1)/2) + j-i];
}
void lt_matrix::display(){
//display matrix
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cout<<get(i,j)<<" ";
}
cout<<"\n";
}
}
int main(){
lt_matrix m;
m.set_all();
m.display();
}