C Online Compiler
Example: Maximum Element in Column - With Input Validation
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Maximum Element in Column - With Input Validation #include
#include
// Required for INT_MIN // Function to find the maximum element in a specified column with validation // Parameters: // matrix: The 2D array (matrix) // rows: Number of rows in the matrix // cols: Number of columns in the matrix // target_column: The 0-indexed column to search // Returns: The maximum element in the target_column, or INT_MIN if validation fails. int findMaxInColumnValidated(int matrix[][4], int rows, int cols, int target_column) { // Step 1: Validate the target_column index if (target_column < 0 || target_column >= cols) { printf("Error: Invalid column index (%d). Must be between 0 and %d.\n", target_column, cols - 1); return INT_MIN; // Return a distinct error value } // Step 2: Validate if there are any rows to process if (rows <= 0) { printf("Error: Matrix has no rows.\n"); return INT_MIN; } // Step 3: Initialize max_element with the first element of the target column int max_element = matrix[0][target_column]; // Step 4: Iterate through the rows to find the maximum for (int i = 1; i < rows; i++) { if (matrix[i][target_column] > max_element) { max_element = matrix[i][target_column]; } } return max_element; } int main() { // Step 1: Define the matrix and its dimensions int matrix[3][4] = { {10, 20, 15, 30}, {25, 12, 18, 22}, {14, 35, 28, 16} }; int rows = 3; int cols = 4; int valid_column = 1; int invalid_column_high = 4; // Out of bounds int invalid_column_low = -1; // Out of bounds printf("Matrix:\n"); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { printf("%4d", matrix[i][j]); } printf("\n"); } printf("\n"); // Step 2: Test with a valid column int result_valid = findMaxInColumnValidated(matrix, rows, cols, valid_column); if (result_valid != INT_MIN) { printf("Maximum element in valid column %d is: %d\n", valid_column, result_valid); } // Step 3: Test with an invalid column (too high) int result_invalid_high = findMaxInColumnValidated(matrix, rows, cols, invalid_column_high); if (result_invalid_high != INT_MIN) { printf("Maximum element in invalid column %d is: %d\n", invalid_column_high, result_invalid_high); } // Step 4: Test with an invalid column (too low) int result_invalid_low = findMaxInColumnValidated(matrix, rows, cols, invalid_column_low); if (result_invalid_low != INT_MIN) { printf("Maximum element in invalid column %d is: %d\n", invalid_column_low, result_invalid_low); } return 0; }
Output
Clear
ADVERTISEMENTS