-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQues-15.cpp
118 lines (94 loc) · 2.31 KB
/
Ques-15.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
112
113
114
115
116
117
118
/*
QUESTION-15:
Write a program to convert the Sparse Matrix into non-zero form and vice-versa.
SOLUTION:
*/
#include<iostream>
using namespace std;
void StoN()
{
int val, arrM[20][20], S[20][3], r=0, c=0, j;
cout<<"\n Enter the no of non-zero elements: ";
cin>>val;
cout<<"\n Enter S. Mat.\n (Row\tCols\tValue):\n";
for(int i=0; i<val; i++)
for(j=0; j<3; j++)
cin>>S[i][j];
// finding rows and cols in main mat.
for(int i=0; i<val; i++)
{
r = (S[i][0] > r) ? S[i][0] : r;
c = (S[i][1] > c) ? S[i][1] : c;
}
for(int i=0; i<=r; i++)
for(j=0; j<=c; j++)
arrM[i][j] = 0;
for(int i=0; i<val; i++)
arrM[S[i][0]][S[i][1]] = S[i][2];
cout<<"\nYour mat.: \n";
for(int i=0; i<=r; i++)
{
for(j=0; j<=c; j++)
cout<<arrM[i][j]<<"\t";
cout<<endl;
}
}
void NtoS()
{
int r, c, arrM[20][20], rS=0, S[20][3], C=0;
cout<<"\n Enter the no. of rows and cols: ";
cin>>r>>c;
cout<<"\n Enter Mat.:\n";
for(int i=0; i<r; i++)
for(int j=0; j<c; j++)
{
cin>>arrM[i][j];
if(arrM[i][j] != 0)
rS++;
}
//making S. Mat
for(int i=0; i<r && C != rS; i++)
for(int j=0; j<c && C != rS; j++)
{
if(arrM[i][j] != 0)
{
S[C][0] = i;
S[C][1] = j;
S[C][2] = arrM[i][j];
C++;
}
}
cout<<"\n\nSparse Mat: \n\n (Row\tCols\tValue):\n";
for(int i=0; i<rS; i++)
{
for(int j=0; j<3; j++)
{
cout<<S[i][j]<<"\t";
}
cout<<"\n";
}
}
int main()
{
int choice;
char ch;
menu:
cout << "\n\t ~~~~~~~~~~~~~~~~~~~~~~~Practical 15~~~~~~~~~~~~~~~~~~~~\n\t\t\t\t \n";
cout<<"\n\nMENU\n"
<<"\n1) Normal matrix to Sparse Mat."
<<"\n2) Sparse Mat to Normal Matrix."
<<"\n\n* Your choice: ";
cin>>choice;
switch(choice)
{
case 1: NtoS();
break;
case 2: StoN();
break;
default: cout<<"\n Invalid input!";
}
cout<<"\n Wanna try again? (Y/N): ";
cin>>ch;
if(ch == 'y' || ch == 'Y')
goto menu;
}