Write a c program on 2D array to Increase & Decrease No of subarrays
#include <stdio.h>
#include <stdlib.h>
// Function to increase the number of rows in a 2D array
int** increaseRows(int** array, int currentRows, int currentCols, int newRows) {
int** newArray = (int**)malloc(newRows * sizeof(int*));
for (int i = 0; i < newRows; i++) {
newArray[i] = (int*)malloc(currentCols * sizeof(int));
if (i < currentRows) {
for (int j = 0; j < currentCols; j++) {
newArray[i][j] = array[i][j];
}
} else {
for (int j = 0; j < currentCols; j++) {
newArray[i][j] = 0; // Initialize new rows with 0
}
}
}
for (int i = 0; i < currentRows; i++) {
free(array[i]);
}
free(array);
return newArray;
}
// Function to decrease the number of rows in a 2D array
int** decreaseRows(int** array, int currentRows, int currentCols, int newRows) {
if (newRows >= currentRows) {
printf("New row count must be less than the current row count.\n");
return array;
}
int** newArray = (int**)malloc(newRows * sizeof(int*));
for (int i = 0; i < newRows; i++) {
newArray[i] = (int*)malloc(currentCols * sizeof(int));
for (int j = 0; j < currentCols; j++) {
newArray[i][j] = array[i][j];
}
}
for (int i = 0; i < currentRows; i++) {
free(array[i]);
}
free(array);
return newArray;
}
// 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; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
}
int main() {
int rows = 3, cols = 3;
int** array = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
array[i] = (int*)malloc(cols * sizeof(int));
for (int j = 0; j < cols; j++) {
array[i][j] = i * cols + j + 1; // Initialize with some values
}
}
printf("Original array:\n");
printArray(array, rows, cols);
// Increase the number of rows
int newRows = 5;
array = increaseRows(array, rows, cols, newRows);
rows = newRows;
printf("Array after increasing rows:\n");
printArray(array, rows, cols);
// Decrease the number of rows
newRows = 2;
array = decreaseRows(array, rows, cols, newRows);
rows = newRows;
printf("Array after decreasing rows:\n");
printArray(array, rows, cols);
for (int i = 0; i < rows; i++) {
free(array[i]);
}
free(array);
return 0;
}
Comments
Post a Comment