JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

JavaScript

// Javascript Program to print the Diagonals of a Matrix
	
	let MAX = 100;

	// Function to print the Principal Diagonal
	function printPrincipalDiagonal(mat, n)
	{
		document.write("Principal Diagonal: ");

		for (let i = 0; i < n; i++) {
			for (let j = 0; j < n; j++) {

				// Condition for principal diagonal
				if (i == j) {
					document.write(mat[i][j] + ", ");
				}
			}
		}
		document.write("</br>");
	}

	// Function to print the Secondary Diagonal
	function printSecondaryDiagonal(mat, n)
	{
		document.write("Secondary Diagonal: ");

		for (let i = 0; i < n; i++) {
			for (let j = 0; j < n; j++) {

				// Condition for secondary diagonal
				if ((i + j) == (n - 1)) {
					document.write(mat[i][j] + ", ");
				}
			}
		}
		document.write("</br>");
	}
	
	let n = 4;
	let a = 
    [ [ 1, 2, 3, 4 ],
			[ 5, 6, 7, 8 ],
			[ 1, 2, 3, 4 ],
			[ 5, 6, 7, 8 ] ];

	printPrincipalDiagonal(a, n);
	printSecondaryDiagonal(a, n);