Skip to main content
Search
Search This Blog
Livecodo
Pages
Home
Courses
Blog
About us
More…
Share
Get link
Facebook
X
Pinterest
Email
Other Apps
March 28, 2024
Write a c program on 2D array to Increase & Decrease no. of subarrays
#include
#include
int main() { int **matrix, rows, cols, i, j; // Initialize the 2D array printf("Enter the number of rows: "); scanf("%d", &rows); printf("Enter the number of columns: "); scanf("%d", &cols); matrix = (int **)malloc(rows * sizeof(int *)); for (i = 0; i < rows; i++) { matrix[i] = (int *)malloc(cols * sizeof(int)); } // Initialize the elements of the matrix printf("Enter the elements of the matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { scanf("%d", &matrix[i][j]); } } // Display the original matrix printf("Original Matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } // Increase or decrease the number of subarrays int choice; printf("\nEnter 1 to increase the number of subarrays, 2 to decrease: "); scanf("%d", &choice); if (choice == 1) { // Increase the number of subarrays int newRows; printf("Enter the number of additional rows: "); scanf("%d", &newRows); matrix = (int **)realloc(matrix, (rows + newRows) * sizeof(int *)); for (i = rows; i < rows + newRows; i++) { matrix[i] = (int *)malloc(cols * sizeof(int)); } rows += newRows; } else if (choice == 2) { // Decrease the number of subarrays int removeRows; printf("Enter the number of rows to remove: "); scanf("%d", &removeRows); if (removeRows <= rows) { matrix = (int **)realloc(matrix, (rows - removeRows) * sizeof(int *)); rows -= removeRows; } else { printf("Error: Cannot remove more rows than present.\n"); } } else { printf("Invalid choice.\n"); } // Display the modified matrix printf("\nModified Matrix:\n"); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("%d\t", matrix[i][j]); } printf("\n"); } // Deallocate memory for (i = 0; i < rows; i++) free( matrix[i]); free(matrix); return 0; }
Popular Posts
March 26, 2024
Dynamic Memory allocation in C
May 18, 2024
Searching and sorting Algorithm in C