0% found this document useful (0 votes)
22 views3 pages

Isc Computer Project #5

Uploaded by

Rahul Ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views3 pages

Isc Computer Project #5

Uploaded by

Rahul Ganguly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Program 5:-

Question: Write a program to accept a square matrix and print both the diagonals of it.

Algorithm:

Step 1: START
Step 2: Input n from user
Step 3: Create a double dimension array matrix with order n
Step 4: Set a loop for i=0 till i<n, i increased by 1 each iteration

Sub-Steps:
4.1: Print “Enter n elements in row no. ” + i
4.2: Set an inner loop for j=0 till j<n, j increased by 1 each
iteration
4.3: Input each element from user

Step 5: Print “The original Square Matrix”

Sub-Steps:
5.1: Set a loop for i=0 till i<n, i increased by 1 each
iteration
5.2: Set an inner loop for j=0 till j<n, j increased by 1 each
iteration
5.3: Print each element in order with value of i as row and value of j as column
followed by a blank space
5.4: Print a blank line

Step 6: Print “The Diagonals”

Sub-Steps:
6.1: Set a loop for i=0 till i<n, i increased by 1 each
iteration
6.2: Set an inner loop for j=0 till j<n, j increased by 1 each
iteration
6.3: If i=j || (i+j)=n-1, print the element with value of i as
row and value of j as column, followed by tab,
else print only “\t”
6.4: Print a blank line in outer loop
Step 7: END

Source code:

import java.util.Scanner;

class Diagonal
{

public static void main(String[] args)


{

Scanner sc = new Scanner(System.in);


System.out.print("Order of square matrix: ");
int n = sc.nextInt();

String[][] matrix = new String[n][n];

for (int i = 0; i < n; i++) {


System.out.println("\nEnter " + n + " elements of row " + (i + 1));

for (int j = 0; j < n; j++)


matrix[i][j] = sc.next().trim();

System.out.println("\nThe Square Matrix:-");

for (int i = 0; i < n; i++) {


for (int j = 0; j < n; j++)
System.out.print(matrix[i][j] + " ");
System.out.println();
}

System.out.println("\nDiagonals:-");

for (int i = 0; i < n; i++) {


for (int j = 0; j < n; j++)
if(i==j || (i+j)==n-1) //Condition for diagonals
System.out.print(matrix[i][j] + "\t");
else
System.out.print("\t");
System.out.println();
}

} //end of main

} //end of class

Variable Description:

Variable Name Data Type Description


Stores order of matrix input
n int
by user
Store double dimension array
matrix String[][]
of elements
i int Used to operate for loops
j int Used to operate for loops

Sample Input / Output:

You might also like