fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <stdlib.h>
  4.  
  5. using namespace std;
  6.  
  7. void initialize_matrix(vector< vector<int> > &a, int m, int n)
  8. {
  9. int i, j;
  10.  
  11. // make sure the matrix has the given number of rows,
  12. // and that each row has the right number of elements
  13. // one for each column; number of rows is m, number of
  14. // columns is n
  15.  
  16. a.resize(m);
  17.  
  18. for (i=0; i<m; i++)
  19. a[i].resize(n);
  20.  
  21. // generate the matrix
  22.  
  23. for (i=0; i<m; i++)
  24. for (j=0; j<n; j++)
  25. a[i][j] = drand48()*101; // random integer from 0 to 100
  26. }
  27.  
  28.  
  29. void add_matrices(vector< vector<int> > &result,
  30. vector< vector<int> > &a,
  31. vector< vector<int> > &b)
  32. {
  33. int i, j;
  34. int m = a.size();
  35. int n = a[0].size();
  36.  
  37. result.resize(m);
  38. for (i=0; i<m; i++)
  39. result[i].resize(n);
  40.  
  41. // execute the addition
  42.  
  43. for (i=0; i<m; i++)
  44. for (j=0; j<n; j++)
  45. result[i][j] = a[i][j] + b[i][j];
  46. }
  47.  
  48. void print_matrix(vector< vector<int> > &a)
  49. {
  50. int i, j;
  51. int m = a.size();
  52. int n = a[0].size();
  53.  
  54. for (i=0; i<m; i++)
  55. {
  56. for (j=0; j<n; j++)
  57. cout << a[i][j] << " ";
  58. cout << endl;
  59. }
  60. }
  61.  
  62. int main()
  63. {
  64. int m, n;
  65. vector< vector<int> > a;
  66. vector< vector<int> > b;
  67. vector< vector<int> > c;
  68.  
  69. // read matrix size from input
  70.  
  71. cin >> m;
  72. cin >> n;
  73.  
  74. // set random seed
  75.  
  76. srand48(123);
  77.  
  78. // initialize the matrices a and b
  79.  
  80. initialize_matrix(a, m, n);
  81. initialize_matrix(b, m, n);
  82.  
  83. // add a and b into c
  84.  
  85. add_matrices(c, a, b);
  86.  
  87. // print the matrices
  88.  
  89. cout << endl << "Matrix A:" << endl;
  90. print_matrix(a);
  91.  
  92. cout << endl << "Matrix B:" << endl;
  93. print_matrix(b);
  94.  
  95. cout << endl << "Matrix C = A + B:" << endl;
  96. print_matrix(c);
  97.  
  98. return 0;
  99. }
  100.  
Success #stdin #stdout 0.02s 2824KB
stdin
5 5
stdout
Matrix A:
28 41 93 13 12 
35 63 84 70 15 
78 37 94 14 85 
12 82 39 91 15 
91 53 29 86 35 

Matrix B:
86 74 13 72 86 
75 94 6 92 62 
99 24 55 90 67 
89 64 15 53 93 
46 20 97 30 15 

Matrix C = A + B:
114 115 106 85 98 
110 157 90 162 77 
177 61 149 104 152 
101 146 54 144 108 
137 73 126 116 50