Diagonal Sum of Matrix in C
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

Sum of Diagonal Elements in a Matrix in C: Program to Find Diagonal Sum

šŸ“‘ On this page:
  • Introduction
  • C Program for Diagonal Sum
  • Sample Output
  • Program Explanation
  • Algorithm
  • Practice Exercise
  • Frequently Asked Questions
šŸ“š In this tutorial, you will learn:
  • What are the main diagonal and secondary diagonal of a matrix
  • How to find the sum of diagonal elements in a matrix
  • How to handle both square and non-square matrices
  • Step-by-step explanation of the program
  • Practice exercises to test your understanding

Introduction

In this tutorial, we will learn how to write a C program to find the sum of diagonal elements in a matrix.

In a matrix, there are two diagonals:

  • Main Diagonal: Elements where row index equals column index (i == j)
  • Secondary Diagonal: Elements where row index + column index = size - 1 (i + j = n - 1)

This program is used in many real-world applications, such as:

  • Image processing and computer vision
  • Linear algebra and matrix operations
  • Game development (checking diagonal patterns)
  • Data analysis and statistics

šŸ’” Key Point: The sum of diagonal elements is only defined for square matrices (where number of rows = number of columns). For a matrix of size n Ɨ n, the diagonal sum includes n elements.

C Program to Find Sum of Diagonal Elements in a Matrix

#include <stdio.h>

int main() {
    int rows, cols, i, j;
    int main_diag_sum = 0;
    int sec_diag_sum = 0;
    
    // Ask user for matrix dimensions
    printf("Enter the number of rows: ");
    scanf("%d", &rows);
    printf("Enter the number of columns: ");
    scanf("%d", &cols);
    
    // Check if it's a square matrix
    if(rows != cols) {
        printf("\nāš ļø Diagonal sum is only defined for square matrices.\n");
        printf("Please enter a square matrix (rows = columns).\n");
        return 1;
    }
    
    // Declare matrix
    int matrix[rows][cols];
    
    // Read elements into the matrix
    printf("\nEnter %d elements:\n", rows * cols);
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("matrix[%d][%d] = ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Calculate sum of main diagonal (i == j)
    for(i = 0; i < rows; i++) {
        main_diag_sum += matrix[i][i];
    }
    
    // Calculate sum of secondary diagonal (i + j == n - 1)
    for(i = 0; i < rows; i++) {
        sec_diag_sum += matrix[i][rows - 1 - i];
    }
    
    // Display the matrix
    printf("\nThe matrix is:\n");
    for(i = 0; i < rows; i++) {
        for(j = 0; j < cols; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
    
    // Display results
    printf("\nāœ… Sum of main diagonal elements: %d\n", main_diag_sum);
    printf("āœ… Sum of secondary diagonal elements: %d\n", sec_diag_sum);
    printf("āœ… Total sum of both diagonals: %d\n", main_diag_sum + sec_diag_sum);
    
    return 0;
}

Sample Output

Enter the number of rows: 3
Enter the number of columns: 3

Enter 9 elements:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[1][0] = 4
matrix[1][1] = 5
matrix[1][2] = 6
matrix[2][0] = 7
matrix[2][1] = 8
matrix[2][2] = 9

The matrix is:
1	2	3
4	5	6
7	8	9

āœ… Sum of main diagonal elements: 15
āœ… Sum of secondary diagonal elements: 15
āœ… Total sum of both diagonals: 30

Another Example:

Enter the number of rows: 4
Enter the number of columns: 4

Enter 16 elements:
matrix[0][0] = 1
matrix[0][1] = 2
matrix[0][2] = 3
matrix[0][3] = 4
matrix[1][0] = 5
matrix[1][1] = 6
matrix[1][2] = 7
matrix[1][3] = 8
matrix[2][0] = 9
matrix[2][1] = 10
matrix[2][2] = 11
matrix[2][3] = 12
matrix[3][0] = 13
matrix[3][1] = 14
matrix[3][2] = 15
matrix[3][3] = 16

The matrix is:
1	2	3	4
5	6	7	8
9	10	11	12
13	14	15	16

āœ… Sum of main diagonal elements: 34
āœ… Sum of secondary diagonal elements: 34
āœ… Total sum of both diagonals: 68

Program Explanation

Let's break down the code step by step:

  1. Include Header File: #include <stdio.h> includes the standard input/output library.
  2. Declare Variables:
    • int rows, cols; — dimensions of the matrix
    • int i, j; — loop counters
    • int main_diag_sum = 0; — stores sum of main diagonal
    • int sec_diag_sum = 0; — stores sum of secondary diagonal
  3. Validate Square Matrix: Checks if rows == cols. If not, displays an error message and exits.
  4. Read Matrix: Uses nested loops to read elements into the matrix.
  5. Calculate Main Diagonal Sum: The for loop runs from i = 0 to i = rows-1 and adds matrix[i][i] to main_diag_sum.
  6. Calculate Secondary Diagonal Sum: The for loop runs from i = 0 to i = rows-1 and adds matrix[i][rows - 1 - i] to sec_diag_sum.
  7. Display Results: Prints the matrix and the calculated sums.
  8. Return: return 0; indicates successful program execution.

šŸ“ Note: For odd-sized matrices, the center element is counted twice if we add both diagonals separately. To avoid this, you can use a single loop and check conditions.

Optimized Version: Single Loop

We can calculate both diagonal sums in a single loop for better efficiency:

#include <stdio.h>

int main() {
    int n, i, j;
    int main_diag_sum = 0;
    int sec_diag_sum = 0;
    
    printf("Enter the size of the square matrix: ");
    scanf("%d", &n);
    
    int matrix[n][n];
    
    printf("\nEnter %d elements:\n", n * n);
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            printf("matrix[%d][%d] = ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Calculate both diagonals in a single loop
    for(i = 0; i < n; i++) {
        main_diag_sum += matrix[i][i];           // Main diagonal
        sec_diag_sum += matrix[i][n - 1 - i];    // Secondary diagonal
    }
    
    // If n is odd, the center element is counted twice
    // So subtract it once from the total
    int total_sum = main_diag_sum + sec_diag_sum;
    if(n % 2 == 1) {
        int center = n / 2;
        total_sum -= matrix[center][center];
    }
    
    printf("\nMatrix:\n");
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
    
    printf("\nāœ… Sum of main diagonal: %d\n", main_diag_sum);
    printf("āœ… Sum of secondary diagonal: %d\n", sec_diag_sum);
    printf("āœ… Total sum of both diagonals: %d\n", total_sum);
    
    return 0;
}

Algorithm to Find Diagonal Sum

Step-by-step algorithm:

  1. Start
  2. Read the size of the square matrix (n)
  3. Read n Ɨ n elements into the matrix
  4. Set main_diag_sum = 0 and sec_diag_sum = 0
  5. For i = 0 to n-1:
    • main_diag_sum += matrix[i][i]
    • sec_diag_sum += matrix[i][n - 1 - i]
  6. If n is odd:
    • Subtract the center element from the total sum to avoid double counting
  7. Print the matrix and diagonal sums
  8. End

Visual Example

For a 3Ɨ3 matrix:

Matrix:

1  2  3
4  5  6
7  8  9

Main Diagonal: 1 + 5 + 9 = 15

Secondary Diagonal: 3 + 5 + 7 = 15

Total Sum (without double counting center): 15 + 15 - 5 = 25

Time and Space Complexity

Operation Time Complexity Space Complexity
Reading Matrix O(n²) O(1)
Diagonal Sum O(n) O(1)
Overall O(n²) O(1)

šŸ’» Practice Exercise

Challenge 1: Find the sum of diagonal elements without using array indexing (use pointer arithmetic).

Challenge 2: Find the sum of elements above and below the main diagonal separately.

šŸ” Click to Show Solution for Challenge 2
#include <stdio.h>

int main() {
    int n, i, j;
    int upper_sum = 0;
    int lower_sum = 0;
    
    printf("Enter the size of the square matrix: ");
    scanf("%d", &n);
    
    int matrix[n][n];
    
    printf("\nEnter %d elements:\n", n * n);
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }
    
    // Calculate upper and lower triangle sums
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            if(i < j) {
                upper_sum += matrix[i][j];  // Above main diagonal
            }
            else if(i > j) {
                lower_sum += matrix[i][j];  // Below main diagonal
            }
        }
    }
    
    printf("\nMatrix:\n");
    for(i = 0; i < n; i++) {
        for(j = 0; j < n; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
    
    printf("\nāœ… Sum of elements above main diagonal: %d\n", upper_sum);
    printf("āœ… Sum of elements below main diagonal: %d\n", lower_sum);
    
    return 0;
}

Frequently Asked Questions

1. What is the main diagonal of a matrix?

The main diagonal consists of elements where the row index equals the column index (i == j). For a 3Ɨ3 matrix, it includes elements at positions (0,0), (1,1), and (2,2).

2. What is the secondary diagonal of a matrix?

The secondary (or anti-diagonal) consists of elements where row index + column index = n - 1. For a 3Ɨ3 matrix, it includes elements at positions (0,2), (1,1), and (2,0).

3. How do you handle the center element when adding both diagonals?

For odd-sized matrices, the center element is counted twice. To avoid this, subtract the center element once from the total sum: total = main + sec - matrix[center][center].

4. Can we find diagonal sum without using a 2D array?

Yes, you can use a 1D array to store the matrix in row-major order and access elements using indexing: matrix[i * cols + j].

5. What if the matrix is not square?

The concept of a diagonal is only defined for square matrices. For non-square matrices, you can still access elements where row index equals column index, but it won't form a complete diagonal.

šŸ’” Tip: When working with matrices, always use nested loops to access elements. The outer loop typically controls rows, and the inner loop controls columns.

šŸ“– Related Tutorials

  • Transpose a Matrix in C
  • Matrix Addition in C
  • Matrix Multiplication in C
  • More Array Assignments

Previous Topic: -->> Array Assignments in C   ||   Next topic: -->> Transpose a Matrix in C


šŸ“š Explore More Topics

šŸ—„ļø SQL Interview Questions & Answers

SQL SELECT Statement FAQ SQL Restricting & Sorting Data FAQ SQL Group Functions & Aggregated Data FAQ SQL Multiple Tables (JOINs) FAQ SQL Subqueries FAQ SQL DML Statements (Managing Tables) FAQ SQL Indexes, Synonyms & Sequences FAQ SQL DDL (Tables & Relationships) FAQ SQL Views FAQ SQL Indexing Best Practices FAQ SQL Window & Analytic Functions FAQ

šŸ Python Interview Questions & Answers

Python Interview Questions Python Syntax & Variables FAQ Python Data Types FAQ Python If-Else FAQ Python Loops FAQ Python Functions Interview Q Python String Manipulation FAQ Python Lists & Dictionaries FAQ Python Tuples & Sets FAQ Python Exception Handling FAQ Python OOP Interview Questions

ā˜• Java Interview Questions & Answers

Java Introduction Interview Q Java Development Environment FAQ Java Data Types FAQ Java Control Flow & Operators FAQ Java Basic Input/Output FAQ Java Arrays FAQ Java Strings FAQ Java Methods FAQ Java Basic OOP Concepts FAQ Java Advanced OOP Concepts FAQ Java OOP Best Practices FAQ Java Exception Handling FAQ Java Synchronization FAQ Java Threads & Concurrency FAQ Java Collection Framework FAQ Java File I/O & Serialization FAQ Java Serialization & Deserialization FAQ Java Features FAQ Java Inner & Anonymous Classes FAQ Java Memory Management FAQ Java Packages FAQ Java Wrapper Classes FAQ Java Streams & Lambda FAQ

C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • Conditional Statements
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • Loops Statements
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processing
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.