GCD and Matrix Programs
GCD and Matrix Programs
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "GCD (recursive) of " << a << " and " << b << " is: " << gcdRecursive(a, b)
<< endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "GCD (iterative) of " << a << " and " << b << " is: " << gcdIterative(a, b)
<< endl;
return 0;
}
#include <iostream>
using namespace std;
class Matrix {
int a[10][10], r, c;
public:
void read() {
cout << "Enter rows and columns: ";
cin >> r >> c;
cout << "Enter elements:
";
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
cin >> a[i][j];
}
void display() {
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
cout << a[i][j] << " ";
cout << endl;
}
}
Matrix add(Matrix m) {
Matrix temp;
if (r != m.r || c != m.c) {
cout << "Matrix dimensions do not match for addition.
";
temp.r = temp.c = 0;
} else {
temp.r = r;
temp.c = c;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
temp.a[i][j] = a[i][j] + m.a[i][j];
}
return temp;
}
Matrix multiply(Matrix m) {
Matrix temp;
if (c != m.r) {
cout << "Matrix dimensions incompatible for multiplication.
";
temp.r = temp.c = 0;
} else {
temp.r = r;
temp.c = m.c;
for (int i = 0; i < r; i++)
for (int j = 0; j < m.c; j++) {
temp.a[i][j] = 0;
for (int k = 0; k < c; k++)
temp.a[i][j] += a[i][k] * m.a[k][j];
}
}
return temp;
}
Matrix transpose() {
Matrix temp;
temp.r = c;
temp.c = r;
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
temp.a[j][i] = a[i][j];
return temp;
}
};
int main() {
Matrix m1, m2, result;
int choice;
cout << "Enter first matrix:
";
m1.read();
cout << "Enter second matrix:
";
m2.read();
do {
cout << "\nMenu:\n1. Add\n2. Multiply\n3. Transpose First Matrix\n4. Exit\nEnter
choice: ";
cin >> choice;
switch (choice) {
case 1:
result = m1.add(m2);
cout << "Resultant Matrix:\n";
result.display();
break;
case 2:
result = m1.multiply(m2);
cout << "Resultant Matrix:\n";
result.display();
break;
case 3:
result = m1.transpose();
cout << "Transpose Matrix:\n";
result.display();
break;
}
} while (choice != 4);
return 0;
}