Sheet 2 (Functions) - Q3

 avatar
itsLu
c_cpp
2 months ago
1.1 kB
2
Indexable
Never
/* C. Write a program that takes a 2D array from the user then calls a
function that prints the transpose of this array. */
#include <iostream>
using namespace std;

void printArray (int arr[][3])
{
    for (int r = 0 ; r < 3 ; r++)
    {
        for (int c = 0 ; c < 3 ; c++)
        {
            cout << arr[r][c] << " ";
        }
        cout << endl;
    }
}

void transpose (int arr[][3], int trArray[][3])
{
    for (int r = 0 ; r < 3 ; r++)
    {
        for (int c = 0 ; c < 3 ; c++)
        {
            trArray[c][r] = arr[r][c];
        }
    }
}

int main ()
{
    int arr[3][3], transposed_arr[3][3];
    for (int r = 0 ; r < 3 ; r++)
    {
        for (int c = 0; c < 3 ; c++)
        {
            cout << "Please enter element " << r+1 << c+1 << ": " << endl;
            cin >> arr[r][c];
        }
    }
    cout << "Original Matrix: " << endl;
    printArray(arr);
    cout << endl;
    transpose(arr, transposed_arr);
    printArray(transposed_arr);
    
}

/* for dynamic array: int *arr = new int[n];
for dynamic 2D array: int **arr = new int*[n]; */
Leave a Comment