Write a c program to increase or decrease the existing size of an 1D array.
#include <stdio.h>
#include <stdlib.h>
// Function to print the array
void printArray(int *arr, int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int initialSize, newSize;
// Input the initial size of the array
printf("Enter the initial size of the array: ");
scanf("%d", &initialSize);
// Allocate memory for the initial array
int *arr = (int *)malloc(initialSize * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Input the elements of the initial array
printf("Enter %d elements:\n", initialSize);
for (int i = 0; i < initialSize; i++) {
scanf("%d", &arr[i]);
}
// Print the initial array
printf("Initial array: ");
printArray(arr, initialSize);
// Input the new size of the array
printf("Enter the new size of the array: ");
scanf("%d", &newSize);
// Reallocate memory for the new array
arr = (int *)realloc(arr, newSize * sizeof(int));
if (arr == NULL) {
printf("Memory reallocation failed\n");
return 1;
}
// If the array size increased, input the new elements
if (newSize > initialSize) {
printf("Enter %d new elements:\n", newSize - initialSize);
for (int i = initialSize; i < newSize; i++) {
scanf("%d", &arr[i]);
}
}
// Print the new array
printf("New array: ");
printArray(arr, newSize);
// Free the allocated memory
free(arr);
return 0;
}
Comments
Post a Comment