🏷️ Replace Negative Elements with Zero in a Matrix in C

⬅️ Previous

Replace Negative Elements with Zero in a Matrix in C

Problem: Write a program that replaces all negative numbers in a 2D matrix with zero.

🔍 Explanation:

  • Input the matrix size and elements.
  • Traverse all elements and check if negative.
  • Replace negatives with zero and display updated matrix.

✅ C Program:


#include <stdio.h>

int main() {
    int rows, cols;

    printf("Enter number of rows and columns:\n");
    scanf("%d %d", &rows, &cols);

    int matrix[rows][cols];

    printf("Enter elements of the matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &matrix[i][j]);
        }
    }

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (matrix[i][j] < 0) {
                matrix[i][j] = 0;
            }
        }
    }

    printf("Updated matrix after replacing negative elements with zero:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", matrix[i][j]);
        }
        printf("\n");
    }

    return 0;
}
  

📤 Sample Output:

Updated matrix after replacing negative elements with zero:
5 0 8
0 7 0
4 0 9
  

replace negative numbers with zero in C, replace negative elements in matrix, matrix negative to zero C program, 2D array negative replacement, C programming matrix problems #CProgramming #MatrixOperations #NegativeToZero #2DArray #LearnC #CProgram #CodingInC #CProgrammingTutorial

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ