Program : Sparse Matrix
import java.io.*; // importing input/output package
class Sparse // class definition
{
int a[][]=new int[10][10],i,j,n,m,flag=0; // initializing array
int c[][]=new int[10][10],k,l,s=1; // initializing array
int t[][]=new int[10][10],q=1; // initializing array
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
// invoking input class
public void data() // void function
{
try // Exception handling
{
System.out.println("Enter the no. of rows");
// print statement
n=Integer.parseInt(f.readLine());
System.out.println("Enter the no. of columns");
m=Integer.parseInt(f.readLine()); // converting input received to integer
System.out.println("Enter the elements");
for(i=0;i<n;i++) // looping structure
for(j=0;j<m;j++)
{
a[i][j]=Integer.parseInt(f.readLine());
}
}
catch(Exception e) // catching the user defined exception
{
System.out.println("Error"); // print statement
}
}
public void work() // void function
{
c[0][0]=n; // assignment
c[0][1]=m;
for(i=0;i<n;i++) // looping structure
for(j=0;j<m;j++)
{
if (a[i][j]!=0) // conditional statement
{
c[s][0]=i;
c[s][1]=j;
c[s][2]=a[i][j];
flag=flag+1; // incrementing flag
s=s+1; // incrementing s
}
}
c[0][2]=flag;
System.out.println("The tuple form is:"); // print statement
for(i=0;i<=flag;i++)
{
for(j=0;j<3;j++)
{
System.out.print(" "+c[i][j]); // print statement
}
System.out.println(" "); // print statement
}
}
public void transpose() // void function
{
t[0][0]=c[0][1];
t[0][1]=c[0][0];
t[0][2]=c[0][2];
if (t[0][2]<=0) // conditional statement
{
for(i=0;i<3;i++)
System.out.println(" "+t[0][i]); // print statement
System.exit(0); // exit program
}
else
{
for(k=0;k<m;k++) // looping structure
{
for(l=1;l<=c[0][2];l++) // looping structure
{
if(c[l][2]==k) // conditional statement
{
t[q][0]=c[l][1];
t[q][1]=c[l][0];
t[q][2]=c[l][2];
q=q+1; // incrementing q
}
}
}
System.out.println("The transposed matrix is:");
// print statement
for(i=0;i<=flag;i++)
{
for(j=0;j<3;j++) // looping structure
{
System.out.print(" "+t[i][j]);
}
System.out.println(" "); // print statement
}
}
}
public static void main(String args[]) // main function
{
Sparse ob=new Sparse(); // object decleration
ob.data(); // calling function
ob.work(); // calling function
ob.transpose(); // calling function
}
}
1 comments:
where s d main class......???
wr d 1st cls ends???
Post a Comment