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

Popular posts from this blog

Write a c program to Create a Circular Linked list and perform Following Operations A. Insertion At Beginning B. Insertion At End C. Insertion After a particular node Insertion Before a particular node E. Insertion at specific position F. Search a particular node G. Return a particular node H. Deletion at the beginning I. Deletion at the end J. Deletion after a particular node K. Deletion before a particular node L. Delete a particular node M. Deletion at a specific position

Write a c program to check whether the created linked list is palindrome or not

Write a c program to Create a Circular single Linked list and perform Following Operations A. Insertion After a particular node B. Insertion Before a particular node C. Search a particular node D. Return a particular node E. Deletion before a particular node F. Delete a particular node