-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_mul.cpp
More file actions
63 lines (51 loc) · 1.62 KB
/
matrix_mul.cpp
File metadata and controls
63 lines (51 loc) · 1.62 KB
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
#include <cstdlib> // For rand() and srand()
#include <ctime> // For time()
#include <iomanip> // For std::setw and std::setfill
#include <iostream>
#include <vector>
// const int SIZE = 30; // Changeable matrix size
// Function to print a matrix with improved formatting
void printMatrix(const std::vector<std::vector<int>> &matrix) {
for (const auto &row : matrix) {
std::cout << "| ";
for (const auto &elem : row) {
std::cout << std::setw(4) << elem << " "; // Align columns with setw
}
std::cout << "|\n";
}
std::cout << std::endl;
}
int main(int argc, char* argv[]) {
const int SIZE = argc > 1 ? atoi(argv[1]) : 30;
// Seed random number generator
srand(static_cast<unsigned>(time(0)));
// Initialize matrices A, B, and C
std::vector<std::vector<int>> A(SIZE, std::vector<int>(SIZE));
std::vector<std::vector<int>> B(SIZE, std::vector<int>(SIZE));
std::vector<std::vector<int>> C(SIZE, std::vector<int>(SIZE, 0));
// Fill matrices A and B with random numbers
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
A[i][j] = rand() % 10 + rand(); // Random numbers from 0 to 9
B[i][j] = rand() % 10 + rand();
}
}
// Display Matrix A
std::cout << "Matrix A:\n";
printMatrix(A);
// Display Matrix B
std::cout << "Matrix B:\n";
printMatrix(B);
// Multiply matrices A and B, store result in C
for (int i = 0; i < SIZE; ++i) {
for (int j = 0; j < SIZE; ++j) {
for (int k = 0; k < SIZE; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
// Display Matrix C
std::cout << "Matrix C (A * B):\n";
printMatrix(C);
return 0;
}