PART B · PRESCRIBED EXERCISE 05

Find the trace of a square matrix using a function

Understand the algorithm. Run the code.
Explain the result with confidence.

Read the programOpen the playground
Aim & definitionStep-by-step algorithmWorked sampleExtra test cases3 viva answers

LAB B05 · 01

Understand the task.

Aim: Find the trace of a square matrix using a function.

DEFINITION

Trace of a matrix. The trace of a square matrix is the sum of its main-diagonal elements, whose row and column indexes are equal.

Review the related theory in Unit 4.

LAB B05 · 02

Know what goes in and what comes out.

First the square-matrix order, from 1 to 5. Then order × order integers from -20 to 20, entered row by row.

Sample input

3
1 2 3
4 5 6
7 8 9

Expected output

Trace = 15

Source programs read the documented input directly, without prompt text, so the same sample works in the embedded compiler’s STDIN field.

LAB B05 · 03

Plan the steps before writing code.

  1. Read and validate order.
  2. Read all matrix elements with nested loops.
  3. Call trace(matrix, order).
  4. Inside trace, initialize total to zero and add matrix[i][i] for every valid i.
  5. Return total and display it in main.

LAB B05 · 04

One complete program. Ready to run.

Find the trace of a square matrix using a functionmain.c
#include <stdio.h>
#define MAX 5
int trace(int matrix[][MAX], int order);
int main(void)
{
    int matrix[MAX][MAX], order, i, j;
    if (scanf("%d", &order) != 1 || order < 1 || order > MAX) {
        puts("Enter a square-matrix order from 1 to 5."); return 1;
    }
    for (i = 0; i < order; i++) {
        for (j = 0; j < order; j++) {
            if (scanf("%d", &matrix[i][j]) != 1 || matrix[i][j] < -20 || matrix[i][j] > 20) {
                puts("Enter matrix values from -20 to 20."); return 1;
            }
        }
    }
    printf("Trace = %d\n", trace(matrix, order));
    return 0;
}
int trace(int matrix[][MAX], int order)
{
    int i, total = 0;
    for (i = 0; i < order; i++) total += matrix[i][i];
    return total;
}
EXPECTED OUTPUTTrace = 15

Try this programDownload B05-matrix-trace.c
Compile on your own computer
gcc B05-matrix-trace.c -o program

Run the generated program and enter the sample input. The examples use standard C90-compatible syntax and explicit function declarations. For these learning programs, enter numeric values representable in the stated C types and within the documented ranges.

LAB B05 · 05

Connect each statement to its purpose.

  • The main diagonal is [0][0], [1][1], …, [order - 1][order - 1].
  • The function does not add every matrix element or the opposite diagonal.
  • In a 2D-array parameter, the trailing dimension MAX is specified so the compiler can calculate row strides.
  • order describes the entered square within the fixed MAX × MAX array; main passes it explicitly.

LAB B05 · 06

Follow the sample calculation.

Step or componentWhat happens
Main diagonal1, 5, 9
Running total0 → 1 → 6 → 15
Returntrace returns the integer 15 to main.

LAB B05 · 07

Check more than one input.

Try this input or caseExpected behaviour
Order 1, value -7Trace = -7
3 × 3 identity matrixTrace = 3
Zero matrixTrace = 0

Time and storage

Reading takes O(n²) time. The trace function itself takes O(n) time and O(1) extra working space.

Start with the sample, then test a boundary and a case that changes the result. A correct sample alone does not establish that every input is handled correctly.

LAB B05 · 08

Use the real C compiler.

Choose an example and load it into the embedded C compiler. Select I/O inside the compiler, check the sample STDIN, and press Run. Change the input or edit the source to explore a different case.

Sample input (STDIN)

3
1 2 3
4 5 6
7 8 9

Expected output

Trace = 15

Load the compiler when you’re ready to practise.

Your C workspace

Edit real C code and see real compiler output.

Compiler provided by OneCompiler. Opening the editor connects to that service; code and input you run are processed there. If the embed is unavailable, open the C compiler in a new tab and paste the source below.

View / copy the selected source
#include <stdio.h>
#define MAX 5
int trace(int matrix[][MAX], int order);
int main(void)
{
    int matrix[MAX][MAX], order, i, j;
    if (scanf("%d", &order) != 1 || order < 1 || order > MAX) {
        puts("Enter a square-matrix order from 1 to 5."); return 1;
    }
    for (i = 0; i < order; i++) {
        for (j = 0; j < order; j++) {
            if (scanf("%d", &matrix[i][j]) != 1 || matrix[i][j] < -20 || matrix[i][j] > 20) {
                puts("Enter matrix values from -20 to 20."); return 1;
            }
        }
    }
    printf("Trace = %d\n", trace(matrix, order));
    return 0;
}
int trace(int matrix[][MAX], int order)
{
    int i, total = 0;
    for (i = 0; i < order; i++) total += matrix[i][i];
    return total;
}

LAB B05 · 09

Explain why the program works.

Must a matrix be square to use this trace definition?

Yes. This prescribed exercise uses the standard square-matrix trace.

Why matrix[i][i]?

The equal row and column indexes select the main diagonal.

Is the entire matrix copied into trace?

No. An array parameter is adjusted to a pointer; the original array storage is accessed.

LAB B05 · 10

Build the next skill.

Read the viva answers, try the extra cases, and return to the lab index to mark this exercise as practised.