Write a c program on 2D array to Increase & Decrease elements in the subarrays
#include <stdio.h>
#include <stdlib.h>
// Function to increase the number of elements in a specific row of a 2D array
void increaseElementsInRow(int** array, int row, int currentCols, int newCols) {
array[row] = (int*)realloc(array[row], newCols * sizeof(int));
for (int j = currentCols; j < newCols; j++) {
array[row][j] = 0; // Initialize new elements with 0
}
}
// Function to decrease the number of elements in a specific row of a 2D array
void decreaseElementsInRow(int** array, int row, int newCols) {
array[row] = (int*)realloc(array[row], newCols * sizeof(int));
}
// Function to print the 2D array
void printArray(int** array, int rows, int* cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols[i]; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
}
int main() {
int rows = 3;
int cols[3] = {3, 3, 3}; // Initial number of columns in each row
int** array = (int**)malloc(rows * sizeof(int*));
// Initialize the array with some values
for (int i = 0; i < rows; i++) {
array[i] = (int*)malloc(cols[i] * sizeof(int));
for (int j = 0; j < cols[i]; j++) {
array[i][j] = i * cols[i] + j + 1; // Initialize with some values
}
}
printf("Original array:\n");
printArray(array, rows, cols);
// Increase the number of elements in the second row
int newCols = 5;
increaseElementsInRow(array, 1, cols[1], newCols);
cols[1] = newCols;
printf("Array after increasing elements in the second row:\n");
printArray(array, rows, cols);
// Decrease the number of elements in the first row
newCols = 2;
decreaseElementsInRow(array, 0, newCols);
cols[0] = newCols;
printf("Array after decreasing elements in the first row:\n");
printArray(array, rows, cols);
// Free the allocated memory
for (int i = 0; i < rows; i++) {
free(array[i]);
}
free(array);
return 0;
}
Comments
Post a Comment