Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdlib.h>
- #include <ctime>
- #include <math.h>
- #include <vector>
- #include <algorithm>
- using namespace std;
- int main()
- {
- srand(time(NULL));
- // 1. Ask the user to give the array's dimensions
- cout << "Give me the dimensions of an array (m and n must be >= 2).\n";
- int m,n;
- cout << "First, give me m = number of rows: ";
- cin >> m;
- while(m < 2){
- cout << "First, give me m = number of rows: ";
- cin >> m;
- }
- cout << "Now, give me n = number of columns: ";
- cin >> n;
- while(n < 2){
- cout << "Give me n = number of columns: ";
- cin >> n;
- }
- cout << endl << endl;
- // 2. Initialize the array's elements by giving them a first random value
- double matrix[m][n];
- for(int i=0; i<m; i++){
- for(int j=0; j<n; j++){
- // Firstly, each element will be an integer number from 0 to 99 (inclusive)
- matrix[i][j] = rand() % 100;
- }
- }
- // Now, I will show the elements of the array
- cout << "The array in the beginning is this one: " << endl;
- for(int i=0; i<m; i++){
- for(int j=0; j<n; j++){
- cout << matrix[i][j] << " ";
- }
- cout << endl;
- }
- cout << endl << endl;
- // 3. Now, I will create a vector with "m" values = the "m" sums of the "m" rows of the array
- vector <int> sums = vector <int> ();
- for(int i=0; i<m; i++){
- int sum = 0;
- for(int j=0; j<n; j++){
- sum += matrix[i][j];
- }
- sums.push_back(sum);
- }
- // 4. I divide every single element with its row's sum of elements
- for(int i=0; i<m; i++){
- for(int j=0; j<n; j++){
- matrix[i][j] /= sums[i];
- }
- }
- // Now, I will display the final array: each row has sum = 1
- cout << "The final array is this one: " << endl;
- for(int i=0; i<m; i++){
- for(int j=0; j<n; j++){
- cout << matrix[i][j] << " ";
- }
- cout << endl;
- }
- cout << endl << endl;
- // 5. Explaining
- cout << "Because: \n";
- for(int i=0; i<m; i++){
- for(int j=0; j<n; j++){
- if(j != n-1){
- cout << matrix[i][j] << " + ";
- }
- else{
- cout << matrix[i][j] << " = 1" << endl;
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement