// Program to find rank of given matrix
//Author : P.N.S. JAYANTH (N190339)
#include <stdio.h>
void main(){
int m, n, lastestNonZero, Bottom, col, count = 0, rank = 0, nxtcol;
printf("Enter number of rows : ");
scanf("%d", &m);
printf("Enter number of cols : ");
scanf("%d", &n);
int mat[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
printf("element (%d, %d) : ", i + 1, j + 1);
scanf("%d", &mat[i][j]);
}
}
for(int i = 0; i < m; i++){
printf("[");
for(int j = 0; j < n; j++){
printf("%5d ", mat[i][j]);
}
printf("]\n");
}
printf("\n\n");
//Rank Logic
for(int i = 0; i < m - 1; i++){
for(int j = 0; j < n; j++){
ifblock:
if(mat[i][j] != 0){
lastestNonZero = mat[i][j];
col = j;
break;
}else{
nxtcol = 0;
for(int p = i + 1; p < m; p++){
if(mat[p][j] != 0){
for(int q = 0; q < n; q++){
mat[p][q] = mat[p][q] + mat[i][q];
mat[i][q] = mat[p][q] - mat[i][q];
mat[p][q] = mat[p][q] - mat[i][q];
}
nxtcol++;
break;
}
}
if(nxtcol == 0){
j++;
goto ifblock;
}else{
lastestNonZero = mat[i][j];
col = j;
break;
}
}
}
for(int x = i + 1; x < m; x++){
Bottom = mat[x][col];
for(int j = 0; j < n; j++){
mat[x][j] = (mat[x][j] * lastestNonZero) - (mat[i][j] * Bottom);
}
}
for(int k = 0; k < m; k++){
printf("[");
for(int o = 0; o < n; o++){
printf("%5d ", mat[k][o]);
}
printf("]\n");
}
printf("\n\n");
}
for(int i = 0; i < m; i++){
count = 0;
for(int j = 0; j < n; j++){
if(mat[i][j] == 0){
count++;
}else{
break;
}
}
if(count != n){
rank++;
}
}
printf("\n\nRank of given matrix is : %d\n", rank);
}