Thursday, 6 February 2014

Playing with zeroes in matrices

It is one of the simplest tasks in C++. If an element in a matrix is found to be zero, then make its corresponding row and column to zeroes. Here is the code for the above task.

  1 #include<iostream> 
  2 using namespace std;
  3 class matrix 
  4 { 
  5     int a[50][50]; 
  6     int n,m; 
  7 public: 
  8     matrix(int rows,int cols) 
  9     { 
 10         n=cols; 
 11         m=rows; 
 12         **a=0; 
 13     } 
 14     void create() 
 15     { 
 16         cout<<"Enter elements: "; 
 17         for(int i=0;i<m;i++) 
 18         { 
 19             for(int j=0;j<n;j++) 
 20             { 
 21                 cin>>a[i][j]; 
 22             } 
 23         } 
 24     } 
 25     void zero() 
 26     { 
 27         int *rows=new int[m]; 
 28         int *cols=new int[n]; 
 29          
 30         for(int i=0;i<m;i++) 
 31         { 
 32             for(int j=0;j<n;j++) 
 33             { 
 34                 if(a[i][j]==0) 
 35                 { 
 36                     rows[i]=1; 
 37                     cols[j]=1; 
 38                 } 
 39             }                 
 40                      
 41         } 
 42      
 43         for(int i=0;i<m;i++) 
 44         { 
 45             for(int j=0;j<n;j++) 
 46             { 
 47                 if(rows[i]==1||cols[j]==1) 
 48                     a[i][j]=0; 
 49             } 
 50         } 
 51     } 
 52     void display() 
 53     { 
 54         for(int i=0;i<m;i++) 
 55         { 
 56             for(int j=0;j<n;j++) 
 57             { 
 58                 cout<<a[i][j]<<" "; 
 59             } 
 60             cout<<endl; 
 61         } 
 62     } 
 63  
 64 }; 
 65 int main() 
 66 { 
 67     int x,y; 
 68     cout<<"Enter rows and cols: "; 
 69     cin>>x>>y; 
 70     matrix m(x,y); 
 71     m.create(); 
 72     m.zero(); 
 73     cout<<"\nAfter change:\n"; 
 74     m.display(); 
 75     return 0;
 76 }
If there are any suggestions, please feel free to comment........See you again with a new challenge 

No comments:

Post a Comment