Skip to main content

Pass array; transpose 3×3 matrix

Short answer

The array name gives the address. The transpose function copies element a[i][j] to t[j][i]. In main, read two 3×3 matrices, call transpose on each, and display the transposed matrices.

Explain how array can be passed to a function. Write a program to transpose a 3*3 matrix. Two matrix are input from the main () function and pass to a user defined function with argument as array. The result is displayed from the main function.

Passing an array to a function

Only the array name is written in the function call, for example transpose(a, t);. The name gives the address of the first element, so the called function works on the original array (call by reference) and no copy is made. The parameter is declared as an array (int a[3][3], or int a[][3]); for 2D arrays the column size is compulsory. Changes made to the array inside the function are visible in the caller.

Program

Both matrices are read in main() and passed to the function transpose(a, t), which stores a[i][j] in t[j][i]. The transposed matrices are then displayed from main().

#include <stdio.h>

void transpose(int a[3][3], int t[3][3])
{
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            t[j][i] = a[i][j];
}

int main(void)
{
    int a[3][3], b[3][3], ta[3][3], tb[3][3];
    printf("Enter first matrix (9 values): ");
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            scanf("%d", &a[i][j]);
    printf("Enter second matrix (9 values): ");
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            scanf("%d", &b[i][j]);

    transpose(a, ta);
    transpose(b, tb);

    printf("Transpose of first matrix:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            printf("%4d", ta[i][j]);
        printf("\n");
    }
    printf("Transpose of second matrix:\n");
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++)
            printf("%4d", tb[i][j]);
        printf("\n");
    }
    return 0;
}

Sample run

Input: 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1

Enter first matrix (9 values): Enter second matrix (9 values): Transpose of first matrix:
   1   4   7
   2   5   8
   3   6   9
Transpose of second matrix:
   9   6   3
   8   5   2
   7   4   1

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →