Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Print all the sub diagonal elements of the given square matrix
Next article icon

Construct a matrix with sum equal to the sum of diagonal elements

Last Updated : 23 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an integer N, the task is to construct a matrix of size N2 using positive and negative integers and excluding 0, such that the sum of the matrix is equal to the sum of the diagonal of the matrix.

Examples: 

Input: N = 2 
Output: 
1 -2 
2 4 
Explanation: 
Diagonal sum = (1 + 4) = 5 
Matrix sum = (1 - 2 + 2 + 4) = 5 

Input: N = 5 
Output: 
1 2 3 5 10 
3 1 4 -9 1 
-19 6 1 5 -8 
4 -7 2 1 12 
-17 1 1 1 1 
Explanation: 
Diagonal sum = (1 + 1 + 1 + 1 + 1) = 5 
Matrix sum = 5 

Approach: 
The approach to solving the problem is to traverse all indices of the matrix and print a positive element(say y) at the N diagonal positions and equally distribute a single-valued positive and negative integer(say x and -x) in the remaining N2 - N positions.

Below is the implementation of the above approach: 

C++
// C++ program to implement // the above approach #include <bits/stdc++.h>  using namespace std;  // Function to construct matrix with // diagonal sum equal to matrix sum void constructmatrix(int N) {     bool check = true;      for (int i = 0; i < N; i++) {          for (int j = 0; j < N; j++) {              // If diagonal position             if (i == j) {                 cout << 1 << " ";             }              else if (check) {                  // Positive element                 cout << 2 << " ";                 check = false;             }             else {                  // Negative element                 cout << -2 << " ";                 check = true;             }         }          cout << endl;     } }  // Driver Code int main() {     int N = 5;      constructmatrix(5);      return 0; } 
Java
// Java program to implement // the above approach public class Main {      // Function to construct matrix with     // diagonal sum equal to matrix sum     public static void constructmatrix(int N)     {         boolean check = true;          for (int i = 0; i < N; i++) {              for (int j = 0; j < N; j++) {                  // If diagonal position                 if (i == j) {                     System.out.print("1 ");                 }                 else if (check) {                      // Positive element                     System.out.print("2 ");                     check = false;                 }                 else {                     // Negative element                     System.out.print("-2 ");                     check = true;                 }             }              System.out.println();         }     }      // Driver Code     public static void main(String[] args)     {         int N = 5;          constructmatrix(5);     } } 
Python3
# Python3 program to implement  # the above approach   # Function to construct matrix with  # diagonal sum equal to matrix sum  def constructmatrix(N):           check = bool(True)       for i in range(N):         for j in range(N):              # If diagonal position              if (i == j):                  print(1, end = " ")              elif (check):                   # Positive element                  print(2, end = " ")                 check = bool(False)                               else:                  # Negative element                  print(-2, end = " ")                 check = bool(True)           print()  # Driver code N = 5 constructmatrix(5)  # This code is contributed by divyeshrabadiya07 
C#
// C# program to implement // the above approach using System;  class GFG{      // Function to construct matrix with // diagonal sum equal to matrix sum public static void constructmatrix(int N) {     bool check = true;      for(int i = 0; i < N; i++)     {         for(int j = 0; j < N; j++)         {                          // If diagonal position             if (i == j)             {                 Console.Write("1 ");             }             else if (check)             {                                  // Positive element                 Console.Write("2 ");                 check = false;             }             else             {                                  // Negative element                 Console.Write("-2 ");                 check = true;             }         }         Console.WriteLine();     } }  // Driver Code static public void Main () {     int N = 5;      constructmatrix(N); } }  // This code is contributed by piyush3010  
JavaScript
<script>  // Javascript program to implement // the above approach       // Function to construct matrix with     // diagonal sum equal to matrix sum     function constructmatrix(N)     {         let check = true;            for (let i = 0; i < N; i++) {                for (let j = 0; j < N; j++) {                    // If diagonal position                 if (i == j) {                     document.write("1 ");                 }                 else if (check) {                        // Positive element                     document.write("2 ");                     check = false;                 }                 else {                     // Negative element                     document.write("-2 ");                     check = true;                 }             }                document.write("<br/>");         }     }      // Driver Code              let N = 5;        constructmatrix(5);  </script> 

Output: 
1 2 -2 2 -2  2 1 -2 2 -2  2 -2 1 2 -2  2 -2 2 1 -2  2 -2 2 -2 1

 

Time Complexity: O(N2) 
Auxiliary Space: O(1)
 


Next Article
Print all the sub diagonal elements of the given square matrix

D

divyeshrabadiya07
Improve
Article Tags :
  • Greedy
  • Mathematical
  • Matrix
  • Competitive Programming
  • DSA
  • array-rearrange
Practice Tags :
  • Greedy
  • Mathematical
  • Matrix

Similar Reads

  • Row-wise common elements in two diagonals of a square matrix
    Given a square matrix, find out count of numbers that are same in same row and same in both primary and secondary diagonals. Examples : Input : 1 2 1 4 5 2 0 5 1 Output : 2 Primary diagonal is 1 5 1 Secondary diagonal is 1 5 0 Two elements (1 and 5) match in two diagonals and same. Input : 1 0 0 0 1
    4 min read
  • Center element of matrix equals sums of half diagonals
    Given a matrix of odd order i.e(5*5). Task is to check if the center element of the matrix is equal to the individual sum of all the half diagonals. Examples: Input : mat[][] = { 2 9 1 4 -2 6 7 2 11 4 4 2 9 2 4 1 9 2 4 4 0 2 4 2 5 } Output : Yes Explanation : Sum of Half Diagonal 1 = 2 + 7 = 9 Sum o
    7 min read
  • Count rows/columns with sum equals to diagonal sum
    Given an n x n square matrix, count all rows and columns whose sum is equal to the sum of any principal diagonal or secondary diagonal. Examples: Input : n = 3 arr[][] = { {1, 2, 3}, {4, 5, 2}, {7, 9, 10}}; Output : 2 In first example sum of principal diagonal = (1 + 5 + 10) = 16 and sum of secondar
    8 min read
  • Sum of main diagonal elements in a Matrix which are prime
    Given a matrix mat[][] of R rows and C columns. The task is to find the sum of all elements from the main diagonal which are prime numbers. Note: The main diagonals are the ones that occur from Top Left of Matrix Down To Bottom Right Corner. Examples: Input: R = 3, C = 3, mat[][] = {{1, 2, 3}, {0, 1
    14 min read
  • Print all the sub diagonal elements of the given square matrix
    Given a square matrix mat[][] of size n * n. The task is to print all the elements which lie on the sub-diagonal of the given matrix.Examples: Input: mat[][] = { {1, 2, 3}, {3, 3, 4, }, {2, 4, 6}} Output: 3 4Input: mat[][] = { {1, 2, 3, 4}, {3, 3, 4, 4}, {2, 4, 6, 3}, {1, 1, 1, 3}} Output: 3 4 1 Rec
    7 min read
  • Print all the super diagonal elements of the given square matrix
    Given a square matrix mat[][] of size n * n. The task is to print all the elements which lie on the super-diagonal of the given matrix.Examples: Input: mat[][] = { {1, 2, 3}, {3, 3, 4, }, {2, 4, 6}} Output: 2 4Input: mat[][] = { {1, 2, 3, 4}, {3, 3, 4, 4}, {2, 4, 6, 3}, {1, 1, 1, 3}} Output: 2 4 3 A
    4 min read
  • Check if two elements of a matrix are on the same diagonal or not
    Given a matrix mat[][], and two integers X and Y, the task is to check if X and Y are on the same diagonal of the given matrix or not. Examples: Input: mat[][]= {{1, 2}. {3, 4}}, X = 1, Y = 4 Output: YesExplanation:Both X and Y lie on the same diagonal. Input: mat[][]= {{1, 2}. {3, 4}}, X = 2, Y = 4
    7 min read
  • Count of odd sum Submatrix with odd element count in the Matrix
    Given a matrix mat[][] of size N x N, the task is to count the number of submatrices with the following properties: The sum of all elements in the submatrix is odd.The number of elements in the submatrix is odd.Examples: Input: mat[][] = {{1, 2, 3}, {7, 5, 9}, {6, 8, 10}}Output: 8Explanation: As her
    15 min read
  • Program to find the Product of diagonal elements of a matrix
    Given an N * N matrix, the task is to find the product of the elements of left and right diagonal. Examples: Input: arr[] = 1 2 3 4 5 6 7 8 9 7 4 2 2 2 2 1Output: 9408Explanation:Product of left diagonal = 1 * 4 * 6 * 1 = 24Product of right diagonal = 4 * 7 * 7 * 2 = 392Total product = 24 * 392 = 94
    7 min read
  • Find maximum sum from top to bottom row with no adjacent diagonal elements
    Given a matrix A[][] of N * M, the task is to find the maximum sum from the top row to the bottom row after selecting one element from each row with no adjacent diagonal element. Examples: Input: A = { {1, 2, 3, 4}, {8, 7, 6, 5}, {10, 11, 12, 13} } Output: 25 Explanation: Selected elements to give m
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences