/*
Program for searching '0' in a matrix and replacing it's row and column with 0's.
Note: Row and column of only first occurence of '0' will be replaced.
*/
#include<iostream>
using namespace std;
void searchZeros(int **mat, int rows, int cols);
int main()
{
//variable declaration
int **mat, row, column;
//For inputting size of matrix
cout << "Enter size of matrix:\n";
//for rows
do
{
cout << "Rows (Max-10)?\t";
cin >> row;
if (row < 0)
cout << "Invalid Input.....";
} while (row < 0);
//for columns
do
{
cout << "Columns (Max-10)?\t";
cin >> column;
if (column < 0)
cout << "Invalid Input.....";
} while (column < 0);
mat = new int*[row];
for (int i = 0; i < row; i++)
mat[i] = new int[column];
//For inputting matrix elements
cout << "Enter matrix elements:\n";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
cout << "Index [" << i << "][" << j << "]?\t";
cin >> mat[i][j];
}
}
//For formatting output
for (int i = 0; i < 40; i++)
cout << "==";
//For displaying entered matrix
cout << "Entered matrix is:\n\n";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
cout << "\t" << mat[i][j];
cout << endl;
}
searchZeros(mat, row, column);
//For formatting output
for (int i = 0; i < 40; i++)
cout << "==";
//For displaying SUM
cout << "\nMatrix after processing:\n";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
cout << "\t" << mat[i][j];
cout << endl;
}
cout << endl;
return 0;
}
void searchZeros(int **mat, int rows, int cols)
{
int rowi=-1, coli=-1;
//For finding index of '0' element if any
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (mat[r][c] == 0)
{
rowi = r;
coli = c;
break;
}
}
}
//For replacing row and column of element '0' with 0's
if (rowi >= 0 && coli >= 0)
{
//For replacing row
for (int i = 0; i < cols; i++)
mat[rowi][i] = 0;
//For replacing column
for (int i = 0; i < rows; i++)
mat[i][coli] = 0;
}
}
OUTPUT
No comments:
Post a Comment