Posted on by Kalkicode
Code Matrix

Find maximum element in each column of the matrix

The problem to be addressed involves finding the maximum element in each column of a given matrix. A matrix is a two-dimensional array with rows and columns, and the task is to identify and print the largest element in each column.

Problem Statement

Given a matrix with dimensions ROW x COL, where each element is an integer, the objective is to find the maximum element in each column and display those maximum values.

Example

Consider the following matrix:

1  -1  6  3
4   8  5  4
3   4  5  0
2   3  2  3
0   3  5  7

The maximum elements in each column are: 4, 8, 6, and 7.

Idea to Solve

Maximum elements of each row of matrix

To solve this problem, iterate through each column of the matrix and identify the maximum element in that column. Initialize a variable to store the maximum element for each column and update it while traversing the column.

Pseudocode

Here's the pseudocode for the algorithm:

function colMaxElement(matrix):
    for i from 0 to COL-1:
        max_element = matrix[0][i] // Initialize max_element with the first element of the column
        for j from 1 to ROW-1:
            if matrix[j][i] > max_element:
                max_element = matrix[j][i] // Update max_element if a larger element is found
        print max_element

Algorithm Explanation

  1. Define a function colMaxElement that takes a 2D matrix matrix as its input.
  2. Initialize a loop that iterates through each column of the matrix from 0 to COL-1 (inclusive).
  3. Inside the outer loop, initialize a variable max_element with the value of the first element in the current column (matrix[0][i]).
  4. Implement an inner loop that starts from 1 and iterates through each row of the current column (from 1 to ROW-1).
  5. Within the inner loop, compare the current element (matrix[j][i]) with max_element. If the current element is greater than max_element, update max_element with the value of the current element.
  6. After the inner loop completes, print the value of max_element, representing the maximum element in the current column.
  7. The outer loop proceeds to the next column, and the process repeats until all columns are processed.

Program List

Time Complexity

The time complexity of this algorithm is O(ROW * COL), where ROW is the number of rows in the matrix and COL is the number of columns. The algorithm iterates through each element of the matrix exactly once to find the maximum element in each column. The nested loops contribute to the complexity.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment