-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQues-21.cpp
111 lines (101 loc) · 2.19 KB
/
Ques-21.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
QUESTION-21:
Write a program to implement Symmetric Matrix using one-dimensional array.
SOLUTION:
*/
#include <iostream>
using namespace std;
/* Symmetric Matrix Class */
class SymmetricMatrix
{
int *arr;
int size;
public:
SymmetricMatrix(int x)
{
this->size = x;
arr = new int[size];
}
~SymmetricMatrix()
{
delete[] arr;
}
/* To store an element 'n' at index (x, y): (input as 1-indexing) */
void store(int x, int y, int n)
{
if (x < 1 || x > size || y < 1 || y > size)
{
cerr << "Err: Index out of bound.";
exit(1);
}
if (x <= y)
{
int k = (y*(y-1)/2 + (x-1));
arr[k] = n;
}
}
/* To retrive element at index (x, y): (input as 1-indexing) */
int retrieve(int x, int y)
{
if (x < 1 || x > size || y < 1 || y > size)
{
cerr << "Err: Index out of bound.";
exit(1);
return -1;
}
else if (x <= y)
{
int k = (y*(y-1)/2 + (x-1));
return arr[k];
}
else if (x > y)
{
int k = (x*(x-1)/2 + (y-1));
return arr[k];
}
return 0;
}
/* To show all the elements of matrix */
void show()
{
for (int i = 0; i < size; ++i)
{
cout << "\n\t";
for (int j = 0; j < size; ++j)
{
cout << retrieve(i+1, j+1) << " ";
}
}
cout << endl;
}
};
int main()
{
cout << "\n\t ~~~~~~~~~~~~~~~~~~~~~~~Practical 21~~~~~~~~~~~~~~~~~~~~\n\t\t\t\t \n";
int x, y;
/* Take input and store */
cout << "\nEnter the no. of rows: ";
cin >> x;
cout << "Enter the no. of columns: ";
cin>>y;
if (x != y)
{
cerr << "Err: No. of rows and columns must be same.";
exit(1);
}
SymmetricMatrix sym(x);
cout << "Enter the matrix elements (by row):\n";
for (int i = 1; i <= x; ++i)
{
int n;
for (int j = i; j <= x; ++j)
{
cin >> n;
sym.store(i, j, n);
}
}
/* Show matrix */
cout << "\nResultant Symmetric Matrix:\n";
sym.show();
return 0;
}