Table of Contents
Matrix Diagonal Sum
The sum of the matrix diagonals
Algorithm
Example
Output
Conclusion
Home Backend Development C++ C++ program to calculate the sum of diagonals of a matrix

C++ program to calculate the sum of diagonals of a matrix

Sep 07, 2023 pm 08:01 PM
program calculate matrix

C++ program to calculate the sum of diagonals of a matrix

The utilization of 2-dimensional arrays or matrices is extremely advantageous for several applications. Matrix rows and columns are used to hold numbers. We can define 2D Multidimensional arrays are used to represent matrices in C. In this article we will look at how to implement use C to calculate the diagonal sum of a given square matrix.

The matrices have two diagonals, the main diagonal and the secondary diagonal (sometimes referred to as major and minor diagonals). The major diagonal starts from the top-left corner (index [0, 0]) to the bottom-right corner (index [n-1, n-1]) where n is the order of the Square matrix. The main diagonal starts from the upper right corner (index [n-1, 0]) and ends at the lower left corner corner (index [0, n-1]). Let us see the algorithm to find the sum of the elements along with these two diagonals.

The Chinese translation of

Matrix Diagonal Sum

is:

The sum of the matrix diagonals

$$\begin{bmatrix} 8 & 5& 3\newline 6 & 7& 1\newline 2 & 4& 9\ \end{bmatrix},$$

1

2

Sum of all elements in major diagonal: (8 + 7 + 9) = 24

Sum of all elements in minor diagonal: (3 + 7 + 2) = 12

Copy after login

In the previous example, one 3 x 3 matrix was used. We have scanned the diagonals individually and calculated the sum. Let us see the algorithm and implementation for a clear view.

Algorithm

  • Read matrix M as input
  • Consider M with n rows and n columns
  • sum_major := 0
  • sum_minor := 0
  • For the range of i from 0 to n-1, execute
    • for j range from 0 to n - 1, do
      • if i and j are the same, then
        • sum_major := sum_major M[ i ][ j ]
      • end if
      • if (i j) is same as (N - 1), then
        • sum_minor := sum_minor M[ i ][ j ]
      • end if
    • end for
  • end for
  • return sum

Example

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

#include <iostream>

#include <cmath>

#define N 7

using namespace std;

float solve( int M[ N ][ N ] ){

   int sum_major = 0;

   int sum_minor = 0;

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

      for ( int j = 0; j < N; j++ ) {

         if( i == j ) {

            sum_major = sum_major + M[ i ][ j ];

         }

         if( (i + j) == N - 1) {

            sum_minor = sum_minor + M[ i ][ j ];

         }

      }

   }

   cout << "The sum of major diagonal: " << sum_major << endl;

   cout << "The sum of minor diagonal: " << sum_minor << endl;

}

int main(){

   int mat1[ N ][ N ] = {

      {5, 8, 74, 21, 69, 78, 25},

      {48, 2, 98, 6, 63, 52, 3},

      {85, 12, 10, 6, 9, 47, 21},

      {6, 12, 18, 32, 5, 10, 32},

      {8, 45, 74, 69, 1, 14, 56},

      {7, 69, 17, 25, 89, 23, 47},

      {98, 23, 15, 20, 63, 21, 56},

   };

   cout << "For the first matrix: " << endl;

   solve( mat1 );

   int mat2[ N ][ N ] = {

      {6, 8, 35, 21, 87, 8, 26},

      {99, 2, 36, 326, 25, 24, 56},

      {15, 215, 3, 157, 8, 41, 23},

      {96, 115, 17, 5, 3, 10, 18},

      {56, 4, 78, 5, 10, 22, 58},

      {85, 41, 29, 65, 47, 36, 78},

      {12, 23, 87, 45, 69, 96, 12}

   };

   cout << "\nFor the second matrix: " << endl;

   solve( mat2 );

}

Copy after login

Output

1

2

3

4

5

6

7

For the first matrix:

The sum of major diagonal: 129

The sum of minor diagonal: 359

 

For the second matrix:

The sum of major diagonal: 74

The sum of minor diagonal: 194

Copy after login

Conclusion

In this article, we have seen how to calculate the diagonal sums of a given square matrix. The main diagonal runs from the upper left corner to the lower right corner, while the secondary diagonal runs from the lower left corner to the upper right corner. The diagonal line starts from the upper right corner to the lower left corner. To find the sum of these diagonal elements, we loop through all elements. When both row and column index values Same, it represents the main diagonal element when the sum of the two indices is Same as the order n-1 of the matrix, it will be added to the subdiagonal procedure takes two nested loops and we are traversing through all elements present in the 2D array. Therefore, calculating the sum of the two diagonals will take O(n2) time given matrix.

The above is the detailed content of C++ program to calculate the sum of diagonals of a matrix. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to make Google Maps the default map in iPhone How to make Google Maps the default map in iPhone Apr 17, 2024 pm 07:34 PM

The default map on the iPhone is Maps, Apple's proprietary geolocation provider. Although the map is getting better, it doesn't work well outside the United States. It has nothing to offer compared to Google Maps. In this article, we discuss the feasible steps to use Google Maps to become the default map on your iPhone. How to Make Google Maps the Default Map in iPhone Setting Google Maps as the default map app on your phone is easier than you think. Follow the steps below – Prerequisite steps – You must have Gmail installed on your phone. Step 1 – Open the AppStore. Step 2 – Search for “Gmail”. Step 3 – Click next to Gmail app

CUDA's universal matrix multiplication: from entry to proficiency! CUDA's universal matrix multiplication: from entry to proficiency! Mar 25, 2024 pm 12:30 PM

General Matrix Multiplication (GEMM) is a vital part of many applications and algorithms, and is also one of the important indicators for evaluating computer hardware performance. In-depth research and optimization of the implementation of GEMM can help us better understand high-performance computing and the relationship between software and hardware systems. In computer science, effective optimization of GEMM can increase computing speed and save resources, which is crucial to improving the overall performance of a computer system. An in-depth understanding of the working principle and optimization method of GEMM will help us better utilize the potential of modern computing hardware and provide more efficient solutions for various complex computing tasks. By optimizing the performance of GEMM

How to calculate addition, subtraction, multiplication and division in word document How to calculate addition, subtraction, multiplication and division in word document Mar 19, 2024 pm 08:13 PM

WORD is a powerful word processor. We can use word to edit various texts. In Excel tables, we have mastered the calculation methods of addition, subtraction and multipliers. So if we need to calculate the addition of numerical values ​​in Word tables, How to subtract the multiplier? Can I only use a calculator to calculate it? The answer is of course no, WORD can also do it. Today I will teach you how to use formulas to calculate basic operations such as addition, subtraction, multiplication and division in tables in Word documents. Let's learn together. So, today let me demonstrate in detail how to calculate addition, subtraction, multiplication and division in a WORD document? Step 1: Open a WORD, click [Table] under [Insert] on the toolbar, and insert a table in the drop-down menu.

How to write a simple countdown program in C++? How to write a simple countdown program in C++? Nov 03, 2023 pm 01:39 PM

C++ is a widely used programming language that is very convenient and practical in writing countdown programs. Countdown program is a common application that can provide us with very precise time calculation and countdown functions. This article will introduce how to use C++ to write a simple countdown program. The key to implementing a countdown program is to use a timer to calculate the passage of time. In C++, we can use the functions in the time.h header file to implement the timer function. The following is the code for a simple countdown program

Clock app missing in iPhone: How to fix it Clock app missing in iPhone: How to fix it May 03, 2024 pm 09:19 PM

Is the clock app missing from your phone? The date and time will still appear on your iPhone's status bar. However, without the Clock app, you won’t be able to use world clock, stopwatch, alarm clock, and many other features. Therefore, fixing missing clock app should be at the top of your to-do list. These solutions can help you resolve this issue. Fix 1 – Place the Clock App If you mistakenly removed the Clock app from your home screen, you can put the Clock app back in its place. Step 1 – Unlock your iPhone and start swiping to the left until you reach the App Library page. Step 2 – Next, search for “clock” in the search box. Step 3 – When you see “Clock” below in the search results, press and hold it and

How to open a website using Task Scheduler How to open a website using Task Scheduler Oct 02, 2023 pm 11:13 PM

Do you frequently visit the same website at about the same time every day? This can lead to spending a lot of time with multiple browser tabs open and cluttering the browser while performing daily tasks. Well, how about opening it without having to launch the browser manually? It's very simple and doesn't require you to download any third-party apps, as shown below. How do I set up Task Scheduler to open a website? Press the key, type Task Scheduler in the search box, and then click Open. Windows On the right sidebar, click on the Create Basic Task option. In the Name field, enter the name of the website you want to open and click Next. Next, under Triggers, click Time Frequency and click Next. Select how long you want the event to repeat and click Next. Select enable

How to count the number of elements in a list using Python's count() function How to count the number of elements in a list using Python's count() function Nov 18, 2023 pm 02:53 PM

How to use Python's count() function to calculate the number of an element in a list requires specific code examples. As a powerful and easy-to-learn programming language, Python provides many built-in functions to handle different data structures. One of them is the count() function, which can be used to count the number of elements in a list. In this article, we will explain how to use the count() function in detail and provide specific code examples. The count() function is a built-in function of Python, used to calculate a certain

Can't allow access to camera and microphone in iPhone Can't allow access to camera and microphone in iPhone Apr 23, 2024 am 11:13 AM

Are you getting "Unable to allow access to camera and microphone" when trying to use the app? Typically, you grant camera and microphone permissions to specific people on a need-to-provide basis. However, if you deny permission, the camera and microphone will not work and will display this error message instead. Solving this problem is very basic and you can do it in a minute or two. Fix 1 – Provide Camera, Microphone Permissions You can provide the necessary camera and microphone permissions directly in settings. Step 1 – Go to the Settings tab. Step 2 – Open the Privacy & Security panel. Step 3 – Turn on the “Camera” permission there. Step 4 – Inside, you will find a list of apps that have requested permission for your phone’s camera. Step 5 – Open the “Camera” of the specified app

See all articles