-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created a Program that Prints all the Diagonal Elements of a Matrix
- Loading branch information
1 parent
c47315c
commit 89ab669
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import java.lang.*; | ||
import java.util.*; | ||
|
||
public class PrintDiagonalElements { | ||
public static void main(String[] args) { | ||
// Taking input for the matrix dimensions | ||
Scanner sc = new Scanner(System.in); | ||
int n = sc.nextInt(); // number of rows | ||
int m = sc.nextInt(); // number of columns | ||
int[][] C = new int[n][m]; | ||
|
||
// Taking input for the matrix elements | ||
for (int i = 0; i < n; i++) { | ||
for (int j = 0; j < m; j++) { | ||
C[i][j] = sc.nextInt(); | ||
} | ||
} | ||
|
||
// Printing diagonals starting from the first row | ||
for (int col = 0; col < m; col++) { | ||
int r = 0; // Start from the first row | ||
int c = col; // Current column | ||
while (r < n && c >= 0) { | ||
System.out.print(C[r][c] + " "); | ||
r++; // Move down | ||
c--; // Move left | ||
} | ||
} | ||
|
||
// Printing diagonals starting from the second row of the first column | ||
for (int row = 1; row < n; row++) { | ||
int r = row; // Current row | ||
int c = m - 1; // Start from the last column | ||
while (r < n && c >= 0) { | ||
System.out.print(C[r][c] + " "); | ||
r++; // Move down | ||
c--; // Move left | ||
} | ||
} | ||
|
||
System.out.println(); // For a newline after printing all diagonals | ||
} | ||
} |