Coding | Mcqs | Multiple choice questions | Informative | Computer Science | Engineering | Aptitude | Quants | Verbal

INFEED

Function GetMatrixFromArrays

 function getMatrixFromArrays 

The function/method getMatrixFromArrays accepts four arguments M, arr1, N and arr2. M represents the size of the integer array arrl. N represents the size of the integer array arr2 .

The function/method getMatrixFromArrays must return a double pointer representing an integer matrix based on the following conditions.

- The matrix to be formed is always a square matrix because the sum of M and N is always a perfect square.

The square matrix must be filled with all the integers from the array arr1 followed by the array art2 in the order of their occurrence (starting from the 1st row, where left to right in each row).

Your task is to implement the function getMatrixFromArrays so that it passes all the test cases.

Your task is to implement the function getMatrixFromArrays so that it passes all the test cases.


IMPORTANT: Do not write the main() function as it is already defined.


Example Input/Output 1:

Input:

5

10 20 30 40 50

4

99 88 77 66


Output:

Matrix:

10 20 30

40 50 99

88 77 66


Explanation:

Here M = 5 and N = 4.

The sum 5 and 4 is 9, which is a perfect square.

So the size of the square matrix is 3x3.

After filling the square matrix with the integers from the given two arrays, the matrix becomes

10 20 30

40 50 99

88 77 66


Example Input/Output 2:

Input:

7

1 2 3 4 5 6 7

9

10 20 30 40 50 60 70 80 90


Output:

Matrix:

1 2 3 4

5 6 7 10

20 30 40 50

60 70 80 90

Program:

#include<stdio.h>

#include<stdlib.h>

int** getMatrixFromArrays(int M, int arr1[], int N, int arr2[])

{

int d=sqrt(M+N),o=0;

int **newArr=malloc(sizeof(int)*(101));

for(int i=0;i<d;i++)

{newArr[i]=malloc(sizeof(int)*(101));

for(int j=0;j<d;j++)

{if(o<M)

    {newArr[i][j]=arr1[o];

    o++;}

    else

    {

        newArr[i][j]=arr2[o-M];

        o++;

    }

}

}

return newArr;

int main()

{

    int M, N;

    scanf("%d", &M);

    int arr1[M];

    for(int index = 0; index < M; index++)

    {

        scanf("%d", &arr1[index]);

    }

    scanf("%d", &N);

    int arr2[N], SIZE = sqrt(M+N);

    for(int index = 0; index < N; index++)

    {

        scanf("%d", &arr2[index]);

    }

    int **newMatrix = getMatrixFromArrays(M, arr1, N, arr2);

    printf("Matrix:\n");

    for(int row = 0; row < SIZE; row++)

    {

        for(int col = 0; col < SIZE; col++)

        {

            printf("%d ", newMatrix[row][col]);

        }

        printf("\n");

    }

    return 0;

}

Post a Comment

Previous Post Next Post