Print the corner elements and their sum in a 2-D matrix in C Program.

Given a 2D matrix, the challenge is to find and print the corner elements along with their sum. In a matrix, corner elements are located at the four corners: top-left, top-right, bottom-left, and bottom-right positions.

For a matrix mat[r][c] with rows from 0 to r-1 and columns from 0 to c-1, the corner elements are: mat[0][0], mat[0][c-1], mat[r-1][0], and mat[r-1][c-1]. The task is to extract these corner elements and calculate their sum.

Syntax

// Corner elements of a matrix mat[r][c]
mat[0][0]        // Top-left corner
mat[0][c-1]      // Top-right corner  
mat[r-1][0]      // Bottom-left corner
mat[r-1][c-1]    // Bottom-right corner

Example

Input: Enter the matrix elements :
   10 2 10
   2 3 4
   10 4 10
Output: Corner elements are: 10, 10, 10, 10
        Sum of corner elements: 40
10 2 10 2 3 4 10 4 10 3x3 Matrix Corner Elements (highlighted in red)

Algorithm

START
Step 1 ? Define matrix dimensions using #define
Step 2 ? Declare matrix and variables
Step 3 ? Input matrix elements using nested loops
Step 4 ? Calculate sum as: mat[0][0] + mat[0][col-1] + mat[row-1][0] + mat[row-1][col-1]
Step 5 ? Display corner elements and their sum
STOP

Implementation

#include <stdio.h>
#define ROW 3
#define COL 3

int main() {
    int matrix[ROW][COL], i, j, sum = 0;
    
    printf("Enter the matrix elements:
"); for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { scanf("%d", &matrix[i][j]); } } /* Display the matrix */ printf("\nMatrix:
"); for (i = 0; i < ROW; i++) { for (j = 0; j < COL; j++) { printf("%d ", matrix[i][j]); } printf("
"); } /* Calculate and display corner elements */ printf("\nCorner elements are: %d, %d, %d, %d
", matrix[0][0], matrix[0][COL-1], matrix[ROW-1][0], matrix[ROW-1][COL-1]); /* Calculate sum of corner elements */ sum = matrix[0][0] + matrix[0][COL-1] + matrix[ROW-1][0] + matrix[ROW-1][COL-1]; printf("Sum of corner elements: %d
", sum); return 0; }

Output

Enter the matrix elements:
10 2 10
2 3 4
10 4 10

Matrix:
10 2 10 
2 3 4 
10 4 10 

Corner elements are: 10, 10, 10, 10
Sum of corner elements: 40

Key Points

  • Corner elements are always at positions: [0][0], [0][c-1], [r-1][0], and [r-1][c-1]
  • For a 1x1 matrix, all four corners refer to the same element
  • The algorithm works for any matrix size greater than 1x1
  • Time complexity is O(1) for corner element access after matrix input

Conclusion

Finding corner elements in a 2D matrix is straightforward using array indexing. The sum calculation involves accessing the four corner positions and adding their values together for the final result.

Updated on: 2026-03-15T11:50:42+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements