Wednesday 3 August 2011

TO ENTER A MATRIX OF nXn AND PRINT ITS DIAGONALS AS WELL AS THEIR SUM SEPARATELY


TO ENTER A MATRIX OF nXn AND PRINT ITS DIAGONALS AS WELL AS THEIR SUM SEPARATELY

ALGORITHM
Step-1 Start
Step-2 Initialization of variables.
Step-3 Accept the limit value for no. of rows and columns.
Step-4 Declaration of a 2-D array with ‘limit’ as its both subscripts.
Step-5 Run the loop for no. of rows.
Step-6 Run the loop for no. of columns.
Step-7 Store the numbers in the declared array.
Step-8 Change the line.
Step-9 Run the loop for no. of rows.
Step-10 Run the loop for no. of columns.
Step-11 If no. of rows are equal to no. of columns then print the left diagonal and add the value of the left diagonal to a counter variable else, proceed to Step-12.
Step-12 If no. of rows + no. of columns is equal to subscript limit -1 then print the right diagonal and add the value of the right diagonal to a counter variable else, proceed to Step-13.
Step-13 Print horizontal tab (i.e. ‘\t’)
Step-14 Display the sum of both diagonals separately.
Step-15 Exit




PROGRAM
import java.io.*;
class diagonal
{
public static void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter No. of rows and columns");
int n=Integer.parseInt(br.readLine());
int a[][]=new int[n][n];
int i,j,ld=0,rd=0;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
System.out.println("Enter a number");
a[i][j]=Integer.parseInt(br.readLine());
    }
   }
   for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
System.out.print(a[i][j]+"\t");
   
}
    System.out.println();
   }
   System.out.println ("Diagonals are as follows");
   for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
if (i==j)
{
ld=ld+a[i][j];
System.out.print(a[i][j]+"\t");
    }
else if (i+j==n-1)
{
System.out.print(a[i][j]+"\t");
rd=rd+a[i][j];
}
else
{
System.out.print("\t");
    }
    }
System.out.println();

}
System.out.println("Sum of Left Diagonal is "+ld);
System.out.println("Sum of Right Diagonal is "+rd);
    }
}

VARIABLE DESCRIPTION-
VARIABLE USED
DATATYPE
DESCRIPTION

n
Integer type
For storing the value for no. of rows and columns.
a
Integer type
A 2-D array with variable ‘n’ as subscripts.
i
Integer type
For running the loop for no. of rows.
j
Integer type
For running the loop for no. of columns.
ld
Integer type
For storing the sum of the left diagonal.
rd
Integer type
For storing the sum of the right diagonal.
INPUT/OUTPUT-

Enter No. of rows and columns
3
Enter a number
1
Enter a number
2
Enter a number
3
Enter a number
4
Enter a number
5
Enter a number
6
Enter a number
7
Enter a number
8
Enter a number
9
1           2          3         
4          5          6         
7          8          9         
Diagonals are as follows
1                       3         
            5                     
7                      9         
Sum of Left Diagonal is 15
Sum of Right Diagonal is 10

5 comments: