C PROGRAMMING PROGRAM • MATRICES
Find Primary and Secondary Diagonal Sums
Learn how to find primary and secondary diagonal sums using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
3 1 2 3 4 5 6 7 8 9
Sample output
Primary diagonal sum = 15 Secondary diagonal sum = 15
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int size, matrix[10][10], primary = 0, secondary = 0;
scanf("%d", &size);
if (size < 1 || size > 10) return 1;
for (int row = 0; row < size; row++)
for (int column = 0; column < size; column++) scanf("%d", &matrix[row][column]);
for (int index = 0; index < size; index++) {
primary += matrix[index][index];
secondary += matrix[index][size - index - 1];
}
printf("Primary diagonal sum = %d\nSecondary diagonal sum = %d\n", primary, secondary);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Primary diagonal sum = 15 Secondary diagonal sum = 15
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use indices (i,i) for the primary diagonal and (i,n−i−1) for the secondary diagonal.
- Display the computed result.
Use indices (i,i) for the primary diagonal and (i,n−i−1) for the secondary diagonal.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(rows × columns)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
