Home > Net >  My program is breaking before completing all execution
My program is breaking before completing all execution

Time:09-17

I am trying to find the Multiplication of Matrix with its transpose using Vectors. While Running program is not executing after printing my inputted matrix and breaking without doing any loops and athematic operations. Why does my program ended after 2nd for loop? Where I am wrong?

//  Multiplication of Matrix by its Transpose
#include<bits/stdc  .h>
using namespace std;
 
 int main()
 {
 int row,col;
 cout<<"ENTER ROWS:";
 cin>>row;
 cout<<"ENTER COLS:";
 cin>>col;

 vector<vector<int>> vec(row, vector<int> (row,col));
  vector<vector<int>>  tran(row, vector<int> (row,col));

 vector<vector<int>>  ans(row, vector<int> (row,col));

    for(int i=0;i<row;i  )
    {
     for(int j=0;j<col;j  )
     {
          int t;
       cin>>t;
         vec[i][j]=t;
     }
       
    } 
    cout<<"\n"<<"Orignal Matrix:"<<endl;
    for(int i=0;i<row;i  )
    {
       for(int j=0;j<col;j  )
       {
          cout<<vec[i][j]<<" ";
       }
       cout<<"\n";
    }

  for(int i=0;i<row;i  ) // transpose
  {
      for(int j=0;j<col;j  )
      {
          tran[i][j]=vec[j][i];
      }
  }


  
cout<<"\n\nTranspose Matrix: \n\n";

  for(int i=0;i<col;i  )
  {
      for(int j=0;j<row;j  )
      {
        cout<<tran[i][j]<<" ";
      }
      cout<<endl;
     
  }

 for(int i=0;i<row;i  ) // multiplication
 {
     for(int j=0;j<col;j  )
     {
         ans[i][0]=vec[i][0]*tran[0][j];
         ans[0][j]=vec[0][j]*tran[i][0];


     }
 }
 cout<<"\n\nMultiplied Matrix: \n\n";

  for(int i=0;i<row;i  )
 {
     for(int j=0;j<col;j  )
     {
         cout<<ans[i][j]<<" ";
     }
     cout<<endl;
 }



 } 

Output I am getting:

ENTER ROWS:3
ENTER COLS:5
2 4 5 5 6 
4 6 7 9 0
1 2 3 5 8

Orignal Matrix:
2 4 5 5 6
4 6 7 9 0
1 2 3 5 8 
 

Expected Output:

ENTER ROWS:3
ENTER COLS:5
2 4 5 5 6 
4 6 7 9 0
1 2 3 5 8

Orignal Matrix:
2 4 5 5 6
4 6 7 9 0
1 2 3 5 8 

Transpose Matrix:
2 4 1
4 6 2
5 7 3
6 9 5
6 0 8

Multiplied Matrix: 
106 112 98
112 182 82
98  82  103

CodePudding user response:

Okay, first... There are ways to find out where your program is crashing. At the very least, you can add more cout statements, and it will tell you.

But it's sort of obvious:

  vector<vector<int>> vec(row, vector<int> (row,col));
  vector<vector<int>>  tran(row, vector<int> (row,col));

  for(int i=0;i<row;i  ) // transpose
  {
      for(int j=0;j<col;j  )
      {
          tran[i][j]=vec[j][i];
      }
  }

You declared both vec and tran exactly the same, but you really need to flip number of rows with number of columns for tran.

Consider what's happening. i goes from 0 to 2. That's fine. j goes from 0 to 4. You then do tran[3][0] = vec[0][3].

But tran[3] is past the end of the array, and you get an out of bounds error.

  • Related