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
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ