Removal of 'Zero' Rows and Columns in a Matrix java code example

Example: removal of 'zero' rows and columns in a matrix in java

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int mat[10][10],mat2[10][10];
    int sum[10],flag_r,flag_c;
    int i,i2,j,j2,k;
    int r,c;
    
    scanf("%d %d",&r,&c);

    //Reading matrix
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            scanf("%d",&mat[i][j]);
        }
    } 

    //For rows
    for(i=0;i<10;i++)    //Clearing sum
    sum[i]=0;
   
    for(i=0;i<r;i++)    //Adding rows
    {
        for(j=0;j<c;j++)
        {
            if(mat[i][j]!=0)
            sum[i]=2;
        }
    }
    
    flag_r=0;
    for(i=0,i2=0;i<r;i++)    //Removing zeros from rows
    {         
        if(sum[i]==0)
        {flag_r++;continue;}
        
        for(j=0;j<c;j++)
        {
            mat2[i2][j]=mat[i][j];
        }
        i2++;
    }
    r=r-flag_r;    //Decrementing row size.

    //Copying mat2 to mat 
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            mat[i][j]=mat2[i][j];
        }
    }

    //For columns
    for(i=0;i<10;i++)    //Clearing sum
    sum[i]=0;
    
    for(j=0;j<c;j++)    //Adding columns
    {
        for(i=0;i<r;i++)
        {if(mat[i][j]!=0)sum[j]=2;}
    }
    
    flag_c=0;
    for(j=0,j2=0;j<c;j++)    //Removing zeros from cols
    {                
        if(sum[j]==0)
        {flag_c++;continue;}
        
        for(i=0;i<r;i++)
        {
            mat2[i][j2]=mat[i][j];
        }
        j2++;
    }
    c=c-flag_c;    //Decrementing col size.

    //Copying mat2 to mat 
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            mat[i][j]=mat2[i][j];
        }
    }

    //Output matrix
    for(i=0;i<r;i++)
    {
        for(j=0;j<c;j++)
        {
            if(j==0)            
            printf("%d",mat[i][j]);
            else
            printf(" %d",mat[i][j]);
        }
        printf("\n");
    }
}

Tags:

Java Example