Open In App

Squares of Matrix Diagonal Elements

Last Updated : 21 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an integer matrix mat[][] of odd dimensions, the task is to find the square of the elements of the Primary and Secondary diagonals.

The Primary and Secondary diagonal matrix explanation is given below:

  • Primary Diagonal Elements of a Matrix: The Primary Diagonal Elements are the ones that occur from Top Left of Matrix Down To Bottom Right Corner. The Primary Diagonal is also known as Main Diagonal or Major Diagonal.
  • Secondary Diagonal Elements of a Matrix: The Secondary Diagonal Elements are the ones that occur from Top Right of Matrix Down To Bottom Left Corner. Also known as Minor Diagonal.

Examples:

Input:
mat[][] = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]

Output: 1 25 81
9 25 49

Explanation: Principal Diagonal: {1, 5, 9}, on squaring each element we will get {1, 25, 81}. Secondary Diagonal: {3, 5, 7}, on squaring each element we will get {9, 25, 49}

Input:
mat[][] = [[8]]

Output: 64
64

Explanation: Principal Diagonal: {8}, on squaring each element we will get {64}. Secondary Diagonal: {8}, on squaring each element we will get {64}

[Naive Approach] By traversing on all elements - O(m*n) Time and O(1) Space

The idea is to traverse the matrix in row-column fashion using the nested loops. The outer loop i is used to traverse all the rows and inner loop j is used traverse all the columns of each row. For each index in the matrix, if i == j, it corresponds to the principal diagonal and if i == n-j-1, it corresponds to the secondary diagonal, where n is the count of columns in each row of the matrix. Traverse the matrix twice, firstly for principal diagonal and then for secondary diagonal. For each element of any of the diagonal, print the square of its value.

C++
// CPP program to print squares of
// diagonal elements.
#include <bits/stdc++.h>
using namespace std;

// function to find diagonal square
void diagonalSquare(vector<vector<int>> &mat) {

    if(mat.size() == 0)
        return;

    int row = mat.size(), col = mat[0].size();

    // Traverse the matrix to 
    // find principal diagonal elements
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)

            // if row and column index matches
            // print the squal of element
            if (i == j)
                cout << mat[i][j] * mat[i][j] << " ";

    cout<< endl;

    // Again traverse the matrix to 
    // find secondary diagonal elements
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)

            // if row and column - j - 1 index matches
            // print the square of element
            if (i == col - j - 1)
                cout << mat[i][j] * mat[i][j] << " ";
}

int main() {
    vector<vector<int>> mat = { { 1, 2, 3 },
                    { 4, 5, 6 },
                    { 7, 8, 9 } };
    diagonalSquare(mat);
    return 0;
}
C
// C program to print squares of
// diagonal elements.
#include <stdio.h>

// function to find diagonal square
void diagonalSquare(int mat[][3], int row, int col) {

    if (row == 0)
        return;

    // Traverse the matrix to 
    // find principal diagonal elements
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)

            // if row and column index matches
            // print the square of element
            if (i == j)
                printf("%d ", mat[i][j] * mat[i][j]);

    printf("\n");

    // Again traverse the matrix to 
    // find secondary diagonal elements
    for (int i = 0; i < row; i++)
        for (int j = 0; j < col; j++)

            // if row and column - j - 1 index matches
            // print the square of element
            if (i == col - j - 1)
                printf("%d ", mat[i][j] * mat[i][j]);
}

int main() {
    int mat[3][3] = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 } };
    diagonalSquare(mat, 3, 3);
    return 0;
}
Java
// Java program to print squares of diagonal elements using
// a 2D array
import java.util.*;

class GfG {

    // Function to find diagonal square
    static void diagonalSquare(int[][] mat) {

        if (mat.length == 0)
            return;

        int row = mat.length, col = mat[0].length;

        // Traverse the matrix to find principal diagonal
        // elements
        for (int i = 0; i < row; i++) {
          
            // If row and column index matches, print the
            // square of the element
            System.out.print(mat[i][i] * mat[i][i] + " ");
        }

        System.out.println();

        // Traverse the matrix to find secondary diagonal
        // elements
        for (int i = 0; i < row; i++) {
          
            // If row and column - j - 1 index matches,
            // print the square of the element
            System.out.print(mat[i][col - i - 1]
                                 * mat[i][col - i - 1]
                             + " ");
        }

        System.out.println();
    }

    public static void main(String[] args) {
      
        int[][] mat
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        diagonalSquare(mat);
    }
}
Python
# Python program to print squares of
# diagonal elements.

# function to find diagonal square
def diagonalSquare(mat):

    if len(mat) == 0:
        return

    row = len(mat)
    col = len(mat[0])

    # Traverse the matrix to
    # find principal diagonal elements
    for i in range(row):
        for j in range(col):

            # if row and column index matches
            # print the square of element
            if i == j:
                print(mat[i][j] * mat[i][j], end=" ")

    print()

    # Again traverse the matrix to
    # find secondary diagonal elements
    for i in range(row):
        for j in range(col):

            # if row and column - j - 1 index matches
            # print the square of element
            if i == col - j - 1:
                print(mat[i][j] * mat[i][j], end=" ")

mat = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]
diagonalSquare(mat)
C#
// C# program to print squares of diagonal elements using
// a 2D array
using System;

class GfG {

    // Function to find diagonal squares
    static void diagonalSquare(int[, ] mat) {
        int row = mat.GetLength(0);
        int col = mat.GetLength(1);

        // Traverse the matrix to find principal diagonal
        // elements
        for (int i = 0; i < row; i++) {
          
            // If row and column index matches, print the
            // square of the element
            Console.Write(mat[i, i] * mat[i, i] + " ");
        }

        Console.WriteLine();

        // Traverse the matrix to find secondary diagonal
        // elements
        for (int i = 0; i < row; i++) {
          
            // If row and column - j - 1 index matches,
            // print the square of the element
            Console.Write(mat[i, col - i - 1]
                              * mat[i, col - i - 1]
                          + " ");
        }

        Console.WriteLine();
    }

    static void Main() {

        int[, ] mat
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        diagonalSquare(mat);
    }
}
JavaScript
// Javascript program to print squares of
// diagonal elements.

// function to find diagonal square
function diagonalSquare(mat) {

    if (mat.length === 0)
        return;

    let row = mat.length, col = mat[0].length;

    // Traverse the matrix to 
    // find principal diagonal elements
    for (let i = 0; i < row; i++)
        for (let j = 0; j < col; j++)

            // if row and column index matches
            // print the square of element
            if (i === j)
                console.log(mat[i][j] * mat[i][j]);

    console.log();

    // Again traverse the matrix to 
    // find secondary diagonal elements
    for (let i = 0; i < row; i++)
        for (let j = 0; j < col; j++)

            // if row and column - j - 1 index matches
            // print the square of element
            if (i === col - j - 1)
                console.log(mat[i][j] * mat[i][j]);
}

//driver code
let mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
diagonalSquare(mat);

Output
1 25 81 
9 25 49 

[Efficient Approach] By traversing only on diagonal elements - O(n) Time and O(1) Space

Each row in a matrix has only one diagonal element. Instead of checking every column, we can directly calculate the diagonal indices. For the primary diagonal, row and column indices are equal, so we print the square of mat[i][i]. For the secondary diagonal, the column index is n - i - 1, where n is the number of columns, so we can print square of mat[i][n-i-1].

C++
// C++ program to print squares of
// diagonal elements.
#include <bits/stdc++.h>
using namespace std;

// function to find diagonal square
void diagonalSquare(vector<vector<int>> &mat) {

    if(mat.size() == 0)
        return;

    int row = mat.size(), col = mat[0].size();

    // Traverse the matrix to 
    // find principal diagonal elements
    for (int i = 0; i < row && i<col; i++)
        cout << mat[i][i] * mat[i][i] << " ";

    cout<<endl;

    // Again traverse the matrix to 
    // find secondary diagonal elements
    for (int i = 0; i < row && i<col; i++)
        cout << mat[i][col-i-1] * mat[i][col-i-1] << " ";
}

int main() {
    vector<vector<int>> mat = { { 1, 2, 3 },
                    { 4, 5, 6 },
                    { 7, 8, 9 } };
    diagonalSquare(mat);
    return 0;
}
C
// C program to print squares of
// diagonal elements.
#include <stdio.h>

// function to find diagonal square
void diagonalSquare(int mat[][3], int row, int col) {

    if (row == 0)
        return;

    // Traverse the matrix to 
    // find principal diagonal elements
    for (int i = 0; i < row && i<col; i++)
        printf("%d ", mat[i][i] * mat[i][i]);

    printf("\n");

    // Again traverse the matrix to 
    // find secondary diagonal elements
    for (int i = 0; i < row && i < col; i++)
        printf("%d ", mat[i][col-i-1] * mat[i][col-i-1]);
}

int main() {
    int mat[3][3] = { { 1, 2, 3 },
                      { 4, 5, 6 },
                      { 7, 8, 9 } };
    diagonalSquare(mat, 3, 3);
    return 0;
}
Java
// Java program to print squares of
// diagonal elements.
import java.util.*;

class GfG {

    // Function to find diagonal squares
    static void diagonalSquare(int[][] mat) {
        int row = mat.length;
        int col = mat[0].length; 

        // Traverse the matrix to find principal diagonal
        // elements
        for (int i = 0; i < row && i < col; i++) {
            System.out.print(
                mat[i][i] * mat[i][i]
                + " "); 
        }

        System.out.println();

        // Again traverse the matrix to find secondary
        // diagonal elements
        for (int i = 0; i < row && i < col; i++) {
            System.out.print(
                mat[i][col - i - 1] * mat[i][col - i - 1]
                + " "); 
        }
    }

    public static void main(String[] args) {   
        int[][] mat
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        diagonalSquare(mat);
    }
}
Python
# Python program to print squares of
# diagonal elements.

# function to find diagonal square
def diagonalSquare(mat):

    if len(mat) == 0:
        return

    row = len(mat)
    col = len(mat[0])

    # Traverse the matrix to
    # find principal diagonal elements
    for i in range(min(col,row)):
        print(mat[i][i] * mat[i][i], end=" ")

    print()

    # Again traverse the matrix to
    # find secondary diagonal elements
    for i in range(min(col,row)):
        print(mat[i][col-i-1] * mat[i][col-i-1], end=" ")


mat = [[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]]
diagonalSquare(mat)
C#
// C# program to print squares of
// diagonal elements.
using System;

class GfG {

    // Function to find diagonal squares
    static void diagonalSquare(int[, ] mat) {
        int row = mat.GetLength(0);
        int col = mat.GetLength(1); 

        // Traverse the matrix to find principal diagonal
        // elements
        for (int i = 0; i < row && i < col; i++) {
            Console.Write(
                mat[i, i] * mat[i, i]
                + " ");
        }

        Console.WriteLine();

        // Again traverse the matrix to find secondary
        // diagonal elements
        for (int i = 0; i < row && i < col; i++) {
            Console.Write(
                mat[i, col - i - 1] * mat[i, col - i - 1]
                + " "); 
        }
    }

    static void Main() {
    
        int[, ] mat
            = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        diagonalSquare(mat);
    }
}
JavaScript
// Javascript program to print squares of
// diagonal elements.

// function to find diagonal square
function diagonalSquare(mat) {

    if (mat.length === 0)
        return;

    let row = mat.length, col = mat[0].length;

    // Traverse the matrix to 
    // find principal diagonal elements
    for (let i = 0; i < row && i < col; i++)
        console.log(mat[i][i] * mat[i][i]);

    console.log();

    // Again traverse the matrix to 
    // find secondary diagonal elements
    for (let i = 0; i < row && i < col; i++)
        console.log(mat[i][col-i-1] * mat[i][col-i-1]);
}

//driver code
let mat = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
diagonalSquare(mat);

Output
1 25 81 
9 25 49 

Next Article
Article Tags :
Practice Tags :

Similar Reads